我最近遇到了 node.js/mongodb 模式,据我所知,它返回一个 promise 。
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 中,查询是组合的,但不一定立即运行。它们返回一个查询对象,您可以使用该对象添加或链接其他查询,然后一起执行。
Mongoose 查询不是 promise 。它们有一个 .then()
函数和 async/await
作为方便。可以使用 .exec()
代替 .then()
也用于回调。
您应该使用哪一个?
await collection.find({ ... })
await collection.find({ ... }).exec()
回答:两者都可以。
两者都有一些功能,因此您可以根据自己的方便使用两者中的任何一个。
但是,如果您使用 .exec()
,它会在出现错误/异常时为您提供更好的堆栈跟踪。
更多信息 here .
关于node.js & mongodb : await collection. 异步查找与 collection.find.exec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63191878/