提问者:小点点

使用Mongoose+Node.js的最佳Async/Await方法是什么?


我想知道mongoose的这种异步等待方法是否正确。我仍然需要使用。exec,然后用mongoose返回promise,或者我可以留下类似的东西。下面是我的代码片段:

例如,这是用户控制器:

/* Func to update one user by id */
    const updateUser = async (id, user) => {
    const filter = {_id: id};
    const update = {name: user.name, email: user.email};
    const result = await User.findOneAndUpdate(filter, update, {new: true});
    return result;
   };

这是路线:

/* PATCH update user passing the id in params */
router.patch('/list/:id/update', async (req, res, next) => {
  try {
    const data = await usersController.updateUser(req.params.id, {
      name: req.body.name,
      email: req.body.email,
    });
    res.status(data ? 200 : 404).json({
      result: data,
      message: 'User updated',
    });
  } catch (e) {
    res.status(500).json({
      result: e.toString(),
    });
  }
});

使用mongoose的这种方法是否正确,或者我需要在查询后使用异步调用。exec().then().catch()?


共1个答案

匿名用户

根据mongoose文档,就功能而言,这两者是等价的。但是,他们建议使用,因为这样可以提供更好的堆栈跟踪:

const doc = await Band.findOne({ name: "Guns N' Roses" }); // works

const badId = 'this is not a valid id';
try {
  await Band.findOne({ _id: badId });
} catch (err) {
  // Without `exec()`, the stack trace does **not** include the
  // calling code. Below is the stack trace:
  //
  // CastError: Cast to ObjectId failed for value "this is not a valid id" at path "_id" for model "band-promises"
  //   at new CastError (/app/node_modules/mongoose/lib/error/cast.js:29:11)
  //   at model.Query.exec (/app/node_modules/mongoose/lib/query.js:4331:21)
  //   at model.Query.Query.then (/app/node_modules/mongoose/lib/query.js:4423:15)
  //   at process._tickCallback (internal/process/next_tick.js:68:7)
  err.stack;
}

try {
  await Band.findOne({ _id: badId }).exec();
} catch (err) {
  // With `exec()`, the stack trace includes where in your code you
  // called `exec()`. Below is the stack trace:
  //
  // CastError: Cast to ObjectId failed for value "this is not a valid id" at path "_id" for model "band-promises"
  //   at new CastError (/app/node_modules/mongoose/lib/error/cast.js:29:11)
  //   at model.Query.exec (/app/node_modules/mongoose/lib/query.js:4331:21)
  //   at Context.<anonymous> (/app/test/index.test.js:138:42)
  //   at process._tickCallback (internal/process/next_tick.js:68:7)
  err.stack;
}