I have this schema:
var eventSchema = new mongoose.Schema({
name: String,
tags: [{
tagId: mongoose.Schema.Types.ObjectId,
name: String,
description: String
}],
});
var Event = mongoose.model('Event', eventSchema);
And a array of tags ids, eg:
var arrayOfTagsIds = [23, 55, 71];
// in this example I'm not using real mongo id's, which are strings
How can I use mongoose's find to search Events that have any of these tags?
For example, this event should be in the results because it has tagId 23 and tagId 55:
{
_id: ...,
name: 'Football tournament',
tags: [{ tagId: 23, name: 'football', description: '' },
{ tagId: 55, name: 'tournament', description: '' }]
}
How must be the query inside find function?
I was thinking of using: tags.tagId: {$in: arrayOfTagsIds} but I don't think that is going to work (it doesn't sound okay to use tags.tagId, because tags is an array)
Event
.find({tags.tagId: {$in: arrayOfTagsIds}})
.exec(function (err, events) { ... }
Also, doing this kind of query is too slow?
Yes, you can use dot notation in keys for both embedded sub-documents and arrays. However, you do need to quote your key because it contains a dot:
Event
.find({'tags.tagId': {$in: arrayOfTagsIds}})
.exec(function (err, events) { ... }
To speed up this query you could create an index on 'tags.tagId'.