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 },
})