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

上面的方法似乎不管用。记录还在那里。

有人能修好吗?


当前回答

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

MyModel.findOneAndRemove({field: 'newValue'}, function(err){...});

它只需要一个DB调用。 如果在搜索和删除之前不执行任何删除操作,则使用此方法。

其他回答

我非常喜欢异步/等待功能的Express/Mongoose应用程序中的这种模式:

app.delete('/:idToDelete', asyncHandler(async (req, res) => {
  const deletedItem = await YourModel
    .findByIdAndDelete(req.params.idToDelete) // This method is the nice method for deleting
    .catch(err => res.status(400).send(err.message))

  res.status(200).send(deletedItem)
}))
model.remove({title:'danish'}, function(err){
    if(err) throw err;
});

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

我更喜欢承诺符号,在这里你需要。

Model.findOneAndRemove({_id:id})
    .then( doc => .... )

mongodb .model.find()返回一个查询对象,该对象也有一个remove()函数。

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

否则,您也可以遵循传统的方法,即首先检索文档,然后删除。

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

    doc.remove(callback); //Removes the document
})

以下是在模型对象上您可以执行以下任何操作来删除文档的方法:

yourModelObj.findOneAndRemove(conditions, options, callback)

yourModelObj。findByIdAndRemove(id, options, callback)

yourModelObj。删除(条件,回调);

var query = Comment.remove({ _id: id });
query.exec();

这招对我很管用,试试这个:

const id = req.params.id;
      YourSchema
      .remove({_id: id})
      .exec()
      .then(result => {
        res.status(200).json({
          message: 'deleted',
          request: {
            type: 'POST',
            url: 'http://localhost:3000/yourroutes/'
          }
        })
      })
      .catch(err => {
        res.status(500).json({
          error: err
        })
      });