0

Hey I have one problem with remove nested array from my database, I would like use findOneAndUpdate and $pull. My point is to remove item from reply array. I try find comments item by _id and remove this reply item, but this not working. Please look on my code below.

my schema

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 Answer 1

3

Take ref from 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
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.