0

I am trying to fetch chats for an array of users. Chats schemas are defined like this:

const ChatSchema = new Schema<IChatSchema>(
  {
    messages: [
      {
        type: Schema.Types.ObjectId,
        ref: "MessageSchema",
      },
    ],
    participants: [
      {
        type:Schema.Types.ObjectId,
        ref: "UserSchema",
      }
    ]
  },
  {
    timestamps: true,
  }
);

I have two usersnames 'A' and 'B' and I want to query common chats of those two users. Any idea how to do it?

User schema

const UserSchema = new Schema<IUserSchema>(
  {
    username: {
      type: String,
      required: true,
      unique:true,
    },
  },
  {
    timestamps: true,
  }
);

I tried this approach but did not work.

let chat = await Chats.find({
    participants: { $elemMatch: { username: usernames } },
  })

I also tried this

let chat = await Chats.find({
    "participants.username": { $all: usernames },
  })

1 Answer 1

1

I can think of a few ways:

Option A: Use aggregation to lookup the participants, then match the usernames
Option B: Use find to retrieve the user records from Users, then query Chats for matching ObjectID values
Option C: modify the schema so the chats also contain the usernames, so you can query them directly

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.