首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >猫鼬-更新记录的最佳方法

猫鼬-更新记录的最佳方法
EN

Stack Overflow用户
提问于 2021-06-27 23:00:28
回答 1查看 42关注 0票数 0

我想用猫鼬更新一张唱片。我也见过其他的答案。但它们很老,就像4-5年前一样。

用猫鼬更新记录的最好方法是什么?同时适用于PUTPATCH请求。

目前我是这样做的。但我不认为这是一个很好的方式,模型有很多领域。

代码语言:javascript
复制
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);
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-29 09:16:20

您可以使用findByIdAndUpdate

代码语言:javascript
复制
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);
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68155936

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档