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

ddarikpa  于 2023-08-04  发布在  Go
关注(0)|答案(3)|浏览(116)

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

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操作,它只更新某些字段,而不是像上面的更新那样更新所有字段。这些字段不是标准的,但它们是更新操作的上述字段之一。

4uqofj5v

4uqofj5v1#

你可以试试这个代码片段(虽然没有在本地测试)。我们的想法是只更新Product中的那些字段,这些字段在req. body中提到过。确保你的验证器是安全的,否则你可能会以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,因为你需要一个真实的的文档来比较。更新操作也不会触发模型的保存后钩子。如果你需要它们-你应该先findById(),更新必要的字段,然后在你找到的文档上点击.保存()。希望有帮助

7eumitmz

7eumitmz2#

You could do this as well:
        // define your middlewares here
       // validateObjectId.js
        const mongoose = require('mongoose');
        module.exports = function (req, res, next) {
            if (!mongoose.Types.ObjectId.isValid(req.params.id))
                return res.status(404).send("Invalid ID.");
            next();
        }
        
    // 404.js 
    module.exports = function (str, id) {
        if (!str || !id) throw new Error('the string name and id must be defined');
        return `The ${str} with the given ID (${id}) was not found`;
    }
// import your middlewares into your product route
       const validateObjectId = require('../middleware/validateObjectId'); // respect your middleware path
       const fourOfour = require('../middleware/404'); // respect your middleware path
            
       router.put('/:id', validateObjectId, async (req, res) => {
            const { error } = validateProduct(req.body);
            const { name, description, category, tags, withdrawn, extraData, } = req.body
            if (error) return res.status(400).send(error.details[0].message);
        
            let product = await Product.findById(req.params.id).exec();
            if (!product) return res.status(404).send(fourOfour("Product", req.params.id));
            product = await Product.findByIdAndUpdate(req.params.id, {
                name: name || product.name,
                description: description || product.description,
                category: category || product.category,
                withdrawn: withdrawn || product.withdrawn,
               extraData: extraData || product.extraData
            }, { new: true });
            product = await product.save();
           if (!product) return res.status(404).send(fourOfour("Product", req.params.id));
            res.send(product);
        });

字符串

u1ehiz5o

u1ehiz5o3#

  • 我想更新文章集合中的特定文章,所以我使用了patch方法而不是put方法。**唯一被更改的部分是在(req.body)中 *

app.route(“/articles”).patch(function(req,res)

console.log(req.body)

    Article.updateOne(
        { title: req.params.articleName },
        { $set: req.body }
    ).then(foundArticle => {
        res.send("Succesfully article updated specifically");
    }).catch(err => {
        console.log("Error is: " + err);
    });

})

字符串

相关问题