Mongoose 静态方法填充数组

Posted

技术标签:

【中文标题】Mongoose 静态方法填充数组【英文标题】:Mongoose static method populating an array 【发布时间】: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】:

这就是我的答案/解决方案: 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);
    
    );

【讨论】:

以上是关于Mongoose 静态方法填充数组的主要内容,如果未能解决你的问题,请参考以下文章

Mongoose 模型中的自定义实例或静态方法中的验证错误

Mongoose 中的方法和静态有啥区别?

Mongoose“静态”方法与“实例”方法

如何在 Mongoose 中编写一个获取所有文档的静态方法?

如何声明可与 ESLint 一起使用的 mongoose 静态方法

如何在 Mongoose 的不同文件中分离模式、方法和静态