Mongoose static method populating an array

1.1k Views Asked by At

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:

  1. Can I use populate in a static method?
  2. What is the best way of checking if "tags" contain "tag"?

Thanks for the help.

1

There are 1 best solutions below

0
On BEST ANSWER

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);
    }
    });
}