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

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

有人能修好吗?


当前回答

Remove()已弃用。使用deleteOne(), deleteMany()或bulkWrite()。

我使用的代码

TeleBot.deleteMany({chatID: chatID}, function (err, _) {
                if (err) {
                    return console.log(err);
                }
            });

其他回答

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

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

如果你知道文档的_id,你可以使用findByIdAndDelete(id),这是findOneAndDelete({_id: id})的简写。

import Question from '../models/Question';

const deleteQuestion = (questionId: string) => {
    try {
        Question.findByIdAndDelete(questionId);
    } catch (e) {
        console.error(e);
    }
};

这里的questionId是documentId (_id)

.remove()类似于.find():

MyModel.remove({search: criteria}, function() {
    // removed.
});

我非常喜欢异步/等待功能的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)
}))
db.collection.remove(<query>,
 {
  justOne: <boolean>,
  writeConcern: <document>
})