我有一个猫鼬模式,如:
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);
};问题:
谢谢你的帮助。
发布于 2014-11-25 19:47:52
这就是我的答案/解决方案: 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);
}
});
}https://stackoverflow.com/questions/27113599
复制相似问题