【问题标题】:Mongoose static method populating an arrayMongoose 静态方法填充数组
【发布时间】:2015-01-22 16:22:43
【问题描述】:

我有一个猫鼬模式,例如:

var postSchema = new Schema({
    ...
    tags : [{ type: Schema.Types.ObjectId, ref: 'Tag' }]
});

我正在尝试实现一个静态方法,该方法返回具有特定标签的帖子。比如:

postSchema.statics.searchByTag = function searchByTag (tag, cb) {
  return this.find().populate('tags')
             .where("tags contains the element tag")
             .exec(cb);
};

问题:

  1. 我可以在静态方法中使用填充吗?
  2. 检查“标签”是否包含“标签”的最佳方法是什么?

感谢您的帮助。

【问题讨论】:

    标签: node.js mongoose where mongodb-query mongoose-populate


    【解决方案1】:

    这就是我的答案/解决方案: 1) 是的,以静态方法填充作品; 2)这就是我解决问题的方法,可能不是最有效的方法,但它有效:

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

    【讨论】:

      猜你喜欢
      • 2021-04-04
      • 2016-07-11
      • 2019-01-31
      • 2014-12-05
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多