【问题标题】:node.js & mongodb: await collection.find vs. collection.find.exec for asyncnode.js 和 mongodb:async 的 await collection.find 与 collection.find.exec
【发布时间】:2020-11-21 07:16:26
【问题描述】:

我最近遇到了 node.js/mongodb 模式,据我所知,它返回了一个承诺。 collection.find({ ... }).exec()

我在我的代码中使用:

await collection.find({ ... })

这些有何不同?我应该使用:

await collection.find({ ... }).exec()

这是我目前使用的,它没有问题:

router.get('/me', auth, async (req, res) => {
        const user = await User.findById(req.user.sub).select('email');

        if (!user) return res.status(400).json({ "status": "error", "message": "This user no longer exists." });

        res.json({ "status": "success", "user": user });
});

【问题讨论】:

  • 这能回答你的问题吗? Mongoose - What does the exec function do?
  • 确实如此,但令人困惑的是我的例程工作完美,我不使用“.exec()”并等待。我会用我的确切代码更新问题。

标签: node.js mongoose


【解决方案1】:

在 Mongoose 中,查询是组合的,但不一定立即运行。它们返回一个查询对象,您可以使用该对象向其添加或链接其他查询,然后一起执行。

Mongoose 查询不是承诺。他们有一个.then() 函数和async/await 作为方便。.exec() 也可以用于回调而不是.then()

你应该使用哪一个?

  • await collection.find({ ... })
  • await collection.find({ ... }).exec()

答案:两者都可以。

两者都有一些功能,因此您可以根据自己的方便使用两者中的任何一个。

但是,如果您使用.exec(),它会在出现错误/异常时为您提供更好的堆栈跟踪。 更多信息here

【讨论】:

    猜你喜欢
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 2017-10-15
    • 2019-01-29
    • 2019-09-22
    • 2018-11-27
    • 1970-01-01
    相关资源
    最近更新 更多