1

I have to delete the second comment using index value.. Following is my document structure

{
    "_id" : ObjectId("000000000fea5f24282e715b"),
    "file_name" : "resume_of_ganga_.docx",
    "created_date" : ISODate("2017-11-28T10:29:10.373Z"),
    "updated_date" : ISODate("2017-11-28T12:39:32.148Z"),
    "comments" : [ 
        {
            "created_date" : ISODate("2017-11-28T13:23:51.472Z"),
            "status" : "N",
            "comment_text" : "Yes...",
            "username" : "name"
        }, 
        {
            "created_date" : ISODate("2017-11-28T13:24:15.938Z"),
            "status" : "N",
            "comment_text" : "asdsd",
            "username" : "name"
        }
    ]

}

I have using this following mongoose query..But my comments are not get deleting

 mongo.filemanager.findOneAndUpdate({ "_id": req.body.id},{$pull : {"'comments.' +req.body.c_index" : 1 }},function(err,response){
        console.log("Deleted")

    });

For example am getting index value as 2.. It should delete the second comment...

Thanks in Advance

Vishnu
  • 745
  • 12
  • 32
  • Possible duplicate of [In mongoDb, how do you remove an array element by its index](https://stackoverflow.com/questions/4588303/in-mongodb-how-do-you-remove-an-array-element-by-its-index) – Damaged Organic Dec 01 '17 at 08:00

1 Answers1

1

I tried looking up to see if MongoDB has any such functionality but seems like they don't from what I found.

A workaround could be something like this. Not sure if this can be considered an atomic operation.

const removeCommentAtIndex = (index) => {
    mongo.filemanager.findById(req.body.id, (err, file) => {
        file.comments.splice(index, 1);

        file.save();
    })  
}

I executed the accepted answer for In mongoDb, how do you remove an array element by its index in my test database and IT WORKS

mongo.filemanager.findOneAndUpdate({}, {"$unset" : {"comments.1" : 1 }}) 
mongo.filemanager.findOneAndUpdate({}, {"$pull" : {"comments" : null}})

Note that your req.body.c_index needs to be 1 to remove 2nd comment.

Nandu Kalidindi
  • 6,075
  • 1
  • 23
  • 36
  • 1
    Thank you so much.. you saved my day... splice working perfect I used findbyid..because pull does not give perfect output.. – Vishnu Dec 01 '17 at 08:46