【问题标题】:Removing documents in MongoDB with mongoose using an OR condition使用 OR 条件使用 mongoose 删除 MongoDB 中的文档
【发布时间】:2015-04-04 18:07:53
【问题描述】:

来自this post,我知道我无法使用下面显示的代码完成我需要的工作。但是,我遇到的所有文档都没有给出需要为 mongoose 中的 remove() 函数提供 OR 条件的用例,我不确定它的结构。我需要以下方法才能以某种方式工作...

router.delete('/friend/:id',function(req,res){
    var response = new Response();
    Message.find().or([{'from.id':req.user.id},{'to.id':req.user.id}]).exec(function(err,messages){
        _.each(messages,function(message){
                message.remove(function (err,message) {

                })
            });
        });
    res.send(response.complete());
});

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    remove 方法有两种:Model#remove(实例方法)和Model.remove(静态方法)。

    如果您想一次删除一个文档(以便调用它们的中间件),那么您可以像当前那样使用实例方法。

    如果您想一次性删除所有匹配的文档(绕过任何中间件),那么您可以使用静态方法并在调用中包含条件:

    Message.remove({$or: [{'from.id': req.user.id}, {'to.id': req.user.id}]})
           .exec(function(err){...})
    

    【讨论】:

      猜你喜欢
      • 2013-09-04
      • 2011-05-28
      • 2020-07-29
      • 2014-05-01
      • 2015-08-14
      • 2017-09-28
      • 1970-01-01
      相关资源
      最近更新 更多