简体   繁体   English

deleteMany 显示 0 已删除但实际删除的文档

[英]deleteMany showing 0 deleted but actually deleting the documents

this controller is deleting all the todos of particular user but in response it is showing {n: 0, deletedCount: 0, ok: 1} , does anyone knows the solution of it?这个 controller 正在删除特定用户的所有待办事项,但作为响应它显示{n: 0, deletedCount: 0, ok: 1} ,有人知道它的解决方案吗?

exports.deleteAll = async (req, res) => {

    const { id } = req.user

    console.log('id', id);

    try {
        // const deleteAllTodos = await TodoModel.findByIdAndDelete(id)

        const deleteAllTodos = await TodoModel.deleteMany({ createdBy: id}, function (err) { 

        console.log('err', err) })

        res.send({ success: true, message: "All todos deleted successfully", deleteAllTodos })

    } catch (error) {

        console.log('Error:', error.message);

        res.status(500).json({
            message: "Internal server error",
            success: false,
            error: error.message
        });

    }
}

From mongoose Query guides来自 mongoose 查询指南

Don't mix using callbacks and promises with queries, or you may end up with duplicate operations.不要将回调和 Promise 与查询混合使用,否则您可能会遇到重复的操作。 That's because passing a callback to a query function immediately executes the query, and calling then() executes the query again.这是因为将回调传递给查询 function 会立即执行查询,然后调用 then() 会再次执行查询。

So what you did there was calling deleteMany twice, first using the callback and then using the async/await .因此,您在那里所做的就是调用deleteMany两次,首先使用回调,然后使用async/await The second attempt will try to delete nothing because the first attempt has already deleted them.第二次尝试将尝试删除任何内容,因为第一次尝试已经删除了它们。

You could try using either one:您可以尝试使用任何一种:

...
const deleteAllTodos = await TodoModel.deleteMany({ createdBy: id }).exec();
res.send({ 
    success: true, 
    message: "All todos deleted successfully", 
    deleteAllTodos 
})

Don't worry about error handling using callback as you have already done it with the try/catch block which will catch if any error happened on deleteMany .不要担心使用回调的错误处理,因为您已经使用try/catch块完成了它,如果deleteMany发生任何错误,它将捕获。

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

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