我想用猫鼬更新一张唱片。我也见过其他的答案。但它们很老,就像4-5年前一样。
用猫鼬更新记录的最好方法是什么?同时适用于PUT和PATCH请求。
目前我是这样做的。但我不认为这是一个很好的方式,模型有很多领域。
export const updateTestimonial = asyncHandler(async (req, res) => {
const values = await testimonialSchema.validateAsync(req.body);
const testimonial = await Testimonial.findById(req.params.id);
if (!testimonial) {
return res.status(404).json({ error: 'Testimonial not found' });
}
testimonial.name = values.name;
testimonial.text = values.text;
const updatedTestimonial = await testimonial.save();
res.status(200).json(updatedTestimonial);
});发布于 2021-06-29 09:16:20
您可以使用findByIdAndUpdate
export const updateTestimonial = asyncHandler(async (req, res) => {
const values = await testimonialSchema.validateAsync(req.body);
const testimonial = await Testimonial.findByIdAndUpdate(req.params.id, values, {new : true});
if (!testimonial) {
return res.status(404).json({ error: 'Testimonial not found' });
}
res.status(200).json(testimonial);
});https://stackoverflow.com/questions/68155936
复制相似问题