简体   繁体   English

如何从mongodb中的数组中删除对象?

[英]How delete object from array in mongodb?

i using MongoDb and NodeJs and i have a little problem with deleting object from array of objects.我使用 MongoDb 和 NodeJs,我在从对象数组中删除对象时遇到了一些问题。 Here is my code这是我的代码

router.route('/deleteGuestFromJam/:id').delete(function(req, res){

Jam.find({_id: req.params.id}, function(err, jam){

    jam.guests = _.without(jam.guests, _.findWhere(jam.guests, {id: req.user.id}));

    jam.save(function(err, jam) {
        if (err){
            return res.status(500).send(err)
        }
        console.log(jam.guests)
        return res.status(200).send(jam);
    });

})

And when i call this route the console give me "jam.save is not a function" error.当我调用此路由时,控制台给我“jam.save 不是函数”错误。 Someone can explain me why is it happening ?.有人可以解释我为什么会这样?。 Thx for answers谢谢解答

You can use update like this您可以像这样使用更新

Jam.update({_id: req.params.id}, 
    { $pull: { 
           guests: { 
                  $elemMatch: { id: req.user.id } 
           } 
       } 
     }, function(){....});

It will pull out the matched object from quests array.它将从 quests 数组中拉出匹配的对象。 See mongo docshere 在此处查看 mongo 文档

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

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