[英]How to remove subdocument in mongoose?
我有一个包含许多文档的集合,每个文档都有一个子文档数组
comment : {
_id : ObjectId
name : String,
comments : [commentSchema]
}
commentSchema : {
_id : ObjectId,
commentType : String // can be either 'string' or 'image'
commentData : String
}
现在,我想从整个注释集合中删除“注释”路径中的所有子文档,该路径为commentType =“ image”。
我做了以下
export.removeComments = function(next) {
mongoose.model('comment').find({}, function(err,docs){
if(err) return next(err);
docs.forEach(function(doc, index){
doc.comments.pull({ commentType : 'image'});
//Following also not works
/* var comments = doc.comments;
for(var i =0; i < comments.length; i++ ) {
if(comments[i].commentType == 'image')
doc.comments.remove(comments[i]._id);
}*/
if(index < docs.length - 1) doc.save();
else doc.save(next);
});
});
};
但是上面没有效果。
有帮助吗?
以下为我工作:
刚刚添加了toString()及其相应的子文档ID,因为它是一个Object而不是字符串。 也许删除子文档需要ID的字符串。 如果我错了请纠正我。
mongoose.model('comment').find({}, function(err,docs){
if(err) return next(err);
docs.forEach(function(doc, index){
for(var i =0; i < comments.length; i++ ) {
if(comments[i].commentType == 'image')
doc.comments.remove(comments[i]._id.toString());
}
if(index < docs.length - 1) doc.save();
else doc.save(next);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.