Home > Back-end >  how to pass array of to find in mongoose
how to pass array of to find in mongoose

Time:08-06

I have a conversation schema in which one of the value is this: participants:[] . It is an array of user strings.

I want to get the conversation based on the array which contains user ids. Right now I am doing this:

const selectedConversation = await Conversation.find({
      userIds: { $in: participants },
    });

But the issue with this is that it returns a first conversation in which atleast one user id matches.

participants array look like this ["user id 1","user id 2","user id 3"] , same with userIds

Any workarounds for this one please?

CodePudding user response:

You need to change the userIds as your id field in your schema. Most probably it is _id. Final code will look like this:

const selectedConversation = await Conversation.find({
      _id: { $in: participants },
});

Further reading: https://www.mongodb.com/docs/manual/reference/operator/query/in/

  • Related