【问题标题】:What's the best Async/Await approach using Mongoose + Node.js?使用 Mongoose + Node.js 的最佳异步/等待方法是什么?
【发布时间】:2020-10-16 19:45:18
【问题描述】:

我想知道这种使用猫鼬的异步/等待方法是否正确。我仍然需要使用 .exec 然后用猫鼬返回承诺,否则我可以留下这样的东西。这是我的代码sn-p:

这是用户控制器,例如:

/* 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()?

【问题讨论】:

    标签: node.js mongodb express asynchronous mongoose


    【解决方案1】:

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

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 2010-11-12
      • 1970-01-01
      • 1970-01-01
      • 2017-03-21
      相关资源
      最近更新 更多