Mongoose static method populating an array Mongoose static method populating an array mongoose mongoose

Mongoose static method populating an array


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:

postSchema.statics.searchByTag = function searchByTag (tagId, cb) {    var Posts = [];    this.find({})    .populate('author tags')    .exec(function(err,posts){    if(err){        cb(err);    }else{        posts.forEach(function(post){        post.tags.forEach(function(tag){            if(new String(tag._id).valueOf() == new String(tagId).valueOf()){            Posts.push(post);            }        });                 });        cb(null,Posts);    }    });}