[英]How to remove subdocument in mongoose?
i have a collection which have many document each of which have a subdocument array 我有一个包含许多文档的集合,每个文档都有一个子文档数组
comment : {
_id : ObjectId
name : String,
comments : [commentSchema]
}
commentSchema : {
_id : ObjectId,
commentType : String // can be either 'string' or 'image'
commentData : String
}
Now i want to delete all the subdocuments in path of 'comments', which is of commentType = 'image', from the whole comment collection. 现在,我想从整个注释集合中删除“注释”路径中的所有子文档,该路径为commentType =“ image”。
I have done the following 我做了以下
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);
});
});
};
But above has no effect. 但是上面没有效果。
Any help?? 有帮助吗?
The following worked for me : 以下为我工作:
just added toString() with corresponding subdocument id as it was an Object not a string. 刚刚添加了toString()及其相应的子文档ID,因为它是一个Object而不是字符串。 and perhaps removing subdocument requires string of the id. 也许删除子文档需要ID的字符串。 Correct me if i am wrong. 如果我错了请纠正我。
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.