2017-12-03 215 views
0

嘿我有一個問題,從我的數據庫中刪除嵌套數組,我想使用findOneAndUpdate$pull。我的意思是從reply陣列中刪除項目。我嘗試通過_id找到評論項目並刪除此回覆項目,但這不起作用。請看下面我的代碼。

我的架構

var productSchema = new Schema({ 

description: [{ 
    type: String, 
    require: true, 
}], 
comments: [{ 
    body: { 
     type: String, 
     trim: true, 
    }, 
    author: { 
     type: String, 
    }, 
    date: { 
     type: Date, 
    }, 
    reply: [{ 
     body: { 
      type: String, 
      trim: true, 
     }, 
     author: { 
      type: String, 
     }, date: { 
      type: Date, 
     } 
    }] 
    }] 
}); 

API

router.put('/dashboard/admin/komentarz/odpowiedz/usun/', function(req, res) { 
var currentCourse = req.body._id; // main item id 
var deleteReply = req.body.reply; // reply item id 
var commentId = req.body.commentId // comments item id 
Product.findOneAndUpdate({ _id: currentCourse }, { $pull: { reply: req.body.reply }}, function(err, product){ 
    //some code 
}) 

回答

1

拿裁判從Mongoose, pull from subdocument

Product.findOneAndUpdate({ 
    _id: currentCourse, 
    // make sure sub document have a unique field let take _id 
    "comments._id" : 'commentId' 
}, 
{ 
    $pull: { 
     "comments.$.reply": { 
      _id:'replyId' 
     } 
    } 
}, 
{ 
    upsert:false, 
    new:true 
}, function(err, product){ 
    //some code 
})