I am trying to create a middleware that will check if a conversation between 2 users exists in the database so if doesn't exists it will create a new conversation. I am trying to use moongoose $in with the 2 ids of the users but it returns any conversation where any of the ids are included and i need to retrieve only the conversations where the ids are togethers included in the users array.
Chat.findOne({
users: {
$in: [
mongoose.Types.ObjectId(MYUSER),
mongoose.Types.ObjectId(OTHERID2),
],
},
})
So lets supose "MYUSER" have a conversation with "RANDOMID", and then i start a new conversation with "OTHERID2", mongoose detects that "MYUSER" have already a conversation started but it doesn't check that the conversation is between the 2 users.
Chat Schema
const chatSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
lastMessage: { type: String },
updatedOn: { type: Date, default: Date.now },
users: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
});
You need to replace $in with $all which returns true only if all specified values are contained within an array:
Chat.findOne({
users: {
$all: [
mongoose.Types.ObjectId(MYUSER),
mongoose.Types.ObjectId(OTHERID2),
],
},
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With