最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Node.js和Mongoose中的补丁请求方法

运维笔记admin14浏览0评论

Node.js和Mongoose中的补丁请求方法

Node.js和Mongoose中的补丁请求方法

对于更新,我使用以下代码:

router.put('/:id', async (req, res) => {
  const { error } = validateProduct(req.body); 
  if (error) return res.status(400).send(error.details[0].message);

  const product = await Product.findByIdAndUpdate(req.params.id, 
    { 
     name: req.body.name,
     description: req.body.description,
     category: req.body.category,
     tags: req.body.tags,
     withdrawn: req.body.withdrawn,
     extraData: {
       brand: req.body.extraData.brand,
       quantity: req.body.extraData.quantity,
       type: req.body.extraData.type
     } 
   }, 
   {new: true}
  );

  if (!product) return res.status(404).send('The product with the given ID was not found.');

  res.send(product);
});

我想要做的是创建一个Patch操作,只更新某些字段而不是所有字段作为上面的更新。这些字段不是标准字段,但它们是更新操作的上述字段之一。

回答如下:

你可以尝试这个片段(虽然没有在本地测试)。我们的想法是只更新在req.body中提到的Product中的那些字段。确保您的验证器是安全的,否则您最终可以使用nosql注入。

router.put('/:id', async (req, res) => {
  const { error } = validateProduct(req.body); 
  if (error) return res.status(400).send(error.details[0].message);

  const product = await Product.findById(req.params.id).exec();
  if (!product) return res.status(404).send('The product with the given ID was not found.');

  let query = {$set: {}};
  for (let key in req.body) {
    if (product[key] && product[key] !== req.body[key]) // if the field we have in req.body exists, we're gonna update it
       query.$set[key] = req.body[key];

  const updatedProduct = await Product.updateOne({_id: req.params.id}, query}).exec();

  res.send(product);
});

另外我确信你可以在行中使用lodash,我在那里使用for-in循环;)

这种方法的缺点是它需要2个查询到mongo,因为你需要一个真实的文档来比较它。此外,更新操作不会触发模型的保存挂钩。如果你需要它们 - 你应该首先找到BYId(),更新必要的字段然后在你找到的文件上点击.save()。希望能帮助到你

发布评论

评论列表(0)

  1. 暂无评论