【问题标题】:remove item from nested array using $pull使用 $pull 从嵌套数组中删除项目
【发布时间】:2017-12-03 09:54:07
【问题描述】:

嘿,我有一个从数据库中删除嵌套数组的问题,我想使用findOneAndUpdate$pull。我的意思是从 reply 数组中删除项目。我尝试通过_id 查找 cmets 项目并删除此回复项目,但这不起作用。请看我下面的代码。

我的架构

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
})

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案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
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多