如何解决如果在 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 举报,一经查实,本站将立刻删除。