使用$ pull从嵌套数组中删除项目

时间:2017-12-03 09:54:08

标签: node.js mongodb express mongoose

嘿我在从数据库中删除嵌套数组时遇到一个问题,我想使用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 个答案:

答案 0 :(得分: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
})