我有一个 Mongoose 模式,例如:
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);
};
问题:
- 我可以在静态方法中使用 populate 吗?
- 检查“tags”是否包含“tag”的最佳方法是什么?
感谢您的帮助。
最佳答案
这就是我的答案/解决方案: 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);
}
});
}
关于node.js - Mongoose 静态方法填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27113599/