如果在 Mongoose 中使用 findByIdAndUpdate 发现,是否有更简洁的方法来执行更新并抛出错误?

问题描述

我有一个更新函数来管理对象中的更新,如下所示:

//// THIS IS THE FirsT REQUEST

  let video = await Video.findById(req.params.id);

  if (!req.params.id.match(/^[0-9a-fA-F]{24}$/) || !video) {
    return next(
      new ErrorResponse(`Document not found with id of ${req.params.id}`,404)
    );
  }
  if (
    video.user.toString() !== req.user._id &&
    req.user.role !== 'founder' &&
    req.user.role !== 'subscriber'
  ) {
    return next(
      new ErrorResponse(
        `User ${req.user._id} is not authorized to update this document`,401
      )
    );
  }

//// THIS IS THE SECOND REQUEST

  const loc = await geocoder.geocode(req.body.address);

  video = await Video.findByIdAndUpdate(
    { _id: req.params.id },{
      $set: {
        ...req.body,slug: slugify(req.body.title,{ lower: true }),location: {
          type: `Point`,coordinates: [loc[0].longitude,loc[0].latitude],formattedAddress: loc[0].formattedAddress,street: loc[0].streetName,city: loc[0].city,state: loc[0].stateCode,zipcode: loc[0].zipcode,country: loc[0].countryCode
        }
      }
    },{
      new: true,runValidators: true,setDefaultsOnInsert: true
    }
  );
  res.status(200).json({ success: true,data: video });

如上面的代码所示,我发出了两个请求,一个用于查找和验证 X 对象,另一个用于更新对象...

我想要做的是将第一个请求的逻辑合并到第二个请求中。

有没有办法把它们结合起来?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)