Richard Richard - 2 months ago 8
Javascript Question

Mongo result set with multiple memberIds

I am using Meteor/Mongo with Typescript/Javascript.

I have a chat app I am developing. I get a result set from Mongo.

const chats: Mongo.Cursor<Chat> = Chats.find(
{ memberIds: 'J65'},
{
sort: { lastMessageCreatedAt: -1 },
transform: this.transformChat.bind(this),
fields: { memberIds: 1, lastMessageCreatedAt: 1 }
}
);


This returns the Chats for J65 .

Question

Is it possible to have multiple memberIds? i.e. return the results for more than one matching id

More info

I have tried this with no success, i.e. it returns nothing even though there is a match (no errors though).

let registeredIds: String[] = ['J65', 'J66'];
...
{ memberIds: registeredIds },


this is what is in the database:


[
{
"_id": "CHb8FSuGSfZMPhkrW",
"memberIds": [
"P9",
"J64"
]
},
{
"_id": "uMSJjHheTp7RhGdH3",
"memberIds": [
"P9",
"J65"
]
},
{
"_id": "e6ZMmRaJLPptF63z8",
"memberIds": [
"P9",
"J66"
]
}
]


Answer

You should use the $in operator.

Your code shall look like:

const chats: Mongo.Cursor<Chat> = Chats.find(
  { memberIds: {$in:['J65','J66','J67']},
  {
    sort: { lastMessageCreatedAt: -1 },
    transform: this.transformChat.bind(this),
    fields: { memberIds: 1, lastMessageCreatedAt: 1 } 
  }
);

Refer docs for more information.