簡體   English   中英

如何刪除貓鼬中的子文檔?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM