2

I have a collection with a following data:

{
       "__v": NumberInt(0),
       "_id": ObjectId("565443b1172e19d51f98b0ed"),
       "address": "tohana",
       "comments": [
         {
           "_id": ObjectId("5654455fe088d89c20736e3c"),
           "comment": "good man",
           "uemail": "[email protected]",
           "uname": "dinesh" 
        },
         {
           "_id": ObjectId("565445e471dce6ca20705a84"),
           "comment": "nice person",
           "uemail": "[email protected]",
           "uname": "krishan" 
        },
         {
           "_id": ObjectId("5654460e7aa73bec2064060e"),
           "comment": "bad person",
           "uemail": "Rai",
           "uname": "Rahul" 
        } 
      ],
       "email": "[email protected]"▼,
       "name": "Nishant" 
    }

Can anyone suggest how to remove a subdocument from a 'comments' key having only id of subdocument, I am going to del? for instance i want to del a subdocument with id 5654455fe088d89c20736e3c So this subdocument should be deleted.

Here is code i am using:

var Users = require("../app/models/users"); //userModel

app.post('/deleteComment/:id', function(req, res) {
    var input = JSON.parse(JSON.stringify(req.body));
    var id = req.params.id;//commentId
    var userId = input.id;//userId

    Users.findByIdAndUpdate(userId, {
      '$pull': {
        'comments':{ '_id': new ObjectId(someStringValue) }
       }
    });
});

But this does not delete data.

1 Answer 1

1

Karan,

You would have to make a small adjustment to your code. Your update criteria needs to be wrapped in an object comparing field to key.

app.post('/deleteComment/:id', function(req, res) {
    var commentId = req.params.id; //commentId
    var userId = req.body.id; //userId

    UserAlerts.findOneAndUpdate(
        {userId: userId}, 
        {$pull: {comments: {_id: commentId}}},
        function(err, data){
           if(err) return err;
           console.log(data);
    });
});
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.