简体   繁体   English

使用mongodb删除nodejs中的子文档

[英]Delete sub document in nodejs with mongodb

I have a collection with a following data:我有一个包含以下数据的集合:

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

Can anyone suggest how to remove a subdocument from a 'comments' key having only id of subdocument, I am going to del?任何人都可以建议如何从只有子文档 ID 的“评论”键中删除子文档,我要删除吗? for instance i want to del a subdocument with id 5654455fe088d89c20736e3c So this subdocument should be deleted.例如我想删除一个id为5654455fe088d89c20736e3c的子文档所以这个子文档应该被删除。

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.但这不会删除数据。

app.post('/deleteComment/:id', function(req, res) {
var input = JSON.parse(JSON.stringify(req.body));
var id = req.params.id;
var userId = input.uid;
 Users.findOneAndUpdate(
        {_id: userId}, 
        {$pull: {comments: {_id: id}}},
        function(err, data){
           if(err) return err;
           res.send({data:data});
    });
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM