如何使用Node.js Mongoose删除文档?

TIM*_*MEX 276 javascript authentication mongodb node.js express

FBFriendModel.find({
    id: 333
}, function (err, docs) {
    docs.remove(); //Remove all the documents that match!
});
Run Code Online (Sandbox Code Playgroud)

以上似乎不起作用.记录仍在那里.

有人能解决吗?

Yus*_*f X 471

如果您不想迭代,请尝试FBFriendModel.find({ id:333 }).remove( callback );FBFriendModel.find({ id:333 }).remove().exec();

mongoose.model.find返回一个Query,它有一个remove函数.

  • 我想@hunterloftis已经解决了这个问题,但对于其他人来说,答案是否定的,这不会在个人文档上运行前/后中间件. (11认同)
  • 这是运行前/后删除中间件吗?(一些模型方法绕过文档中间件,我不确定这是否是其中之一,文档不清楚) (3认同)

dio*_*ney 292

由于"mongoose": ">=2.7.1"你可以直接删除文档.remove()的方法,而不是找到文档,然后删除它,这似乎对我来说更高效和易于维护.

见例子:

Model.remove({ _id: req.body.id }, function(err) {
    if (!err) {
            message.type = 'notification!';
    }
    else {
            message.type = 'error';
    }
});
Run Code Online (Sandbox Code Playgroud)

更新:

从mongoose开始3.8.1,有几种方法可以直接删除文档,例如:

  • remove
  • findByIdAndRemove
  • findOneAndRemove

有关详细信息,请参阅mongoose API文档.

  • 正如在对其他答案的其他评论中所指出的,这绕过了在架构上定义的中间件,并且可能非常危险.因此,只有了解了可能产生的影响,才能使用它.有关详细信息,请参阅http://mongoosejs.com/docs/middleware.html (13认同)
  • 如果你不小心传递`query = {}`,`remove(query)`可能会清空你的整个集合*.出于这个原因,如果我只删除*one*文档,我更喜欢`findOneAndRemove(query)`. (8认同)
  • 只是为了记录,直到现在我总是使用它们没有任何副作用,当然,我没有在我的项目中使用任何中间件:) (2认同)

mtk*_*one 47

docs是一系列文件.所以它没有mongooseModel.remove()方法.

您可以单独迭代和删除阵列中的每个文档.

或者 - 因为看起来你是通过一个(可能)唯一的id找到文件 - findOne而不是使用find.

  • 看到这个答案假设一个相当古老的猫鼬版本,我真的不会反对有人改变接受的答案. (5认同)

Jos*_*nto 39

这对我来说是3.8.1版本中最好的:

MyModel.findOneAndRemove({field: 'newValue'}, function(err){...});
Run Code Online (Sandbox Code Playgroud)

它只需要一个DB调用.使用此命令,您不执行任何remove搜索和删除操作.


San*_*nda 32

简单地做

FBFriendModel.remove().exec();
Run Code Online (Sandbox Code Playgroud)

  • 这是一种危险的答案,没有把删除中指定的操作条件... (3认同)

Amo*_*rni 28

mongoose.model.find()返回一个也有函数的查询对象remove().

mongoose.model.findOne()如果您只想删除一个唯一文档,也可以使用.

否则,您可以在首先检索文档然后删除的情况下遵循传统方法.

yourModelObj.findById(id, function (err, doc) {
    if (err) {
        // handle error
    }

    doc.remove(callback); //Removes the document
})
Run Code Online (Sandbox Code Playgroud)

以下是model对象的方法,您可以执行以下任一操作来删除文档:

yourModelObj.findOneAndRemove(conditions, options, callback)
Run Code Online (Sandbox Code Playgroud)

yourModelObj.findByIdAndRemove(id, options, callback)

yourModelObj.remove(conditions, callback);

var query = Comment.remove({ _id: id });
query.exec();
Run Code Online (Sandbox Code Playgroud)


Sam*_*ain 21

remove() has been deprecated. Use deleteOne(), deleteMany() or bulkWrite().

The code I use

TeleBot.deleteMany({chatID: chatID}, function (err, _) {
                if (err) {
                    return console.log(err);
                }
            });
Run Code Online (Sandbox Code Playgroud)

  • 老实说,这个答案需要更多的赞成票。它被不公平地置于桶的底部(因为它没有获得过时的五年投票),但它是解决以下问题的唯一答案:`(node:9132) DeprecationWarning: collection.remove is deprecated . 请改用 deleteOne、deleteMany 或 bulkWrite。` (3认同)

ale*_*anu 18

概括起来,您可以使用:

SomeModel.find( $where, function(err,docs){
  if (err) return console.log(err);
  if (!docs || !Array.isArray(docs) || docs.length === 0) 
    return console.log('no docs found');
  docs.forEach( function (doc) {
    doc.remove();
  });
});
Run Code Online (Sandbox Code Playgroud)

另一种实现此目的的方法是:

SomeModel.collection.remove( function (err) {
  if (err) throw err;
  // collection is now empty but not deleted
});
Run Code Online (Sandbox Code Playgroud)


dam*_*hat 18

小心findOne并删除!

  User.findOne({name: 'Alice'}).remove().exec();
Run Code Online (Sandbox Code Playgroud)

上面的代码删除了名为"Alice"的所有用户,而不是仅删除了第一个用户.

顺便说一句,我更喜欢删除这样的文档:

  User.remove({...}).exec();
Run Code Online (Sandbox Code Playgroud)

或提供回调并省略exec()

  User.remove({...}, callback);
Run Code Online (Sandbox Code Playgroud)


Dan*_*ish 14

model.remove({title:'danish'}, function(err){
    if(err) throw err;
});
Run Code Online (Sandbox Code Playgroud)

参考:http://mongoosejs.com/docs/api.html#model_Model.remove


小智 11

如果您只想要删除一个对象,则可以使用

Person.findOne({_id: req.params.id}, function (error, person){
        console.log("This object will get deleted " + person);
        person.remove();

    });
Run Code Online (Sandbox Code Playgroud)

在此示例中,Mongoose将根据匹配的req.params.id进行删除.


tru*_*ktr 9

.remove()的作用如下.find():

MyModel.remove({search: criteria}, function() {
    // removed.
});
Run Code Online (Sandbox Code Playgroud)


Sim*_*n H 9

我更喜欢承诺符号,例如你需要的地方

Model.findOneAndRemove({_id:id})
    .then( doc => .... )
Run Code Online (Sandbox Code Playgroud)


sat*_*mar 7

为了删除文档,我更喜欢使用 Model.remove(conditions, [callback])

请参阅API文档以进行删除: -

http://mongoosejs.com/docs/api.html#model_Model.remove

对于这种情况,代码将是: -

FBFriendModel.remove({ id : 333 }, function(err, callback){
console.log(‘Do Stuff’);
})
Run Code Online (Sandbox Code Playgroud)

如果要在不等待MongoDB响应的情况下删除文档,不要传递回调,那么需要在返回的Query上调用exec

var removeQuery = FBFriendModel.remove({id : 333 });
removeQuery.exec();
Run Code Online (Sandbox Code Playgroud)


Cha*_*ear 6

您可以直接在remove函数中使用查询,因此:

FBFriendModel.remove({ id: 333}, function(err){});
Run Code Online (Sandbox Code Playgroud)


Dor*_*gal 6

您可以随时使用Mongoose内置功能:

var id = req.params.friendId; //here you pass the id
    FBFriendModel
   .findByIdAndRemove(id)
   .exec()
   .then(function(doc) {
       return doc;
    }).catch(function(error) {
       throw error;
    });
Run Code Online (Sandbox Code Playgroud)


Jos*_*ell 5

更新:.remove()已折旧,但仍适用于旧版本

YourSchema.remove({
    foo: req.params.foo
}, function(err, _) {
    if (err) return res.send(err)
    res.json({
        message: `deleted ${ req.params.foo }`
    })
});
Run Code Online (Sandbox Code Playgroud)