Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find where 2 id are present in Mongoose Array

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" }],
  });
like image 473
JDLR Avatar asked Jan 25 '26 23:01

JDLR


1 Answers

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),
        ],
    },
})
like image 97
mickl Avatar answered Jan 28 '26 14:01

mickl