I have a mongoose schema such as:
var postSchema = new Schema({
...
tags : [{ type: Schema.Types.ObjectId, ref: 'Tag' }]
});
I am trying to implement a static method which returns the posts having a certain tag. Something like:
postSchema.statics.searchByTag = function searchByTag (tag, cb) {
return this.find().populate('tags')
.where("tags contains the element tag")
.exec(cb);
};
Questions:
- Can I use populate in a static method?
- What is the best way of checking if "tags" contain "tag"?
Thanks for the help.
This is then my answer/solution: 1) yes populate works in static methods; 2) This is how I solved the problem, might be not the most efficient way, but it works: