猫鼬-替换所有数组元素

时间:2020-04-26 18:06:27

标签: node.js mongodb mongoose mongodb-query

我要替换“价格”中的所有数组元素,如下所示:

{
 "name": "My customer name"
 "taxCode":123456
 "prices": 
         [
           {
             "name": "Chocolate",
             "unitPrice": 10
           },
           {
             "name": "Cookie",
             "unitPrice": 9
           }
         ]
}

用于更改“价格”的JSON是:

{
 "prices": 
          [
             {
              "name": "Chocolate1", 
              "unitPrice": 10
             },
             {
              "name": "Candy",
              "unitPrice": 5
             }
           ]
}

这是我的代码,用于替换“价格”数组

router.route('/:obj/:id')
  .put((req, res) => {
    const PObj  = require('../models/customer');
    PObj.findById(req.params.id, (err, doc) => {
      if (err) { 
        console.log('Lookup error: ' + err);
        res.status(500).send('Error');
      } else if (doc) {
        doc.update({$set: req.body}, (err, task) => {
          res.status(200).json(task);
        });     } else {
        res.status(404).send('Something is wrong');
      }
    });
  });

执行完代码后,但Mongo DB中没有任何更改。请帮助我更正我的代码。谢谢!

1 个答案:

答案 0 :(得分:1)

如果您的req.body打印该价格数组,则必须为req.body.prices,而不是获取文档并对其进行更新-这是双向过程,您可以尝试以下操作:

router.route("/:obj/:id").put((req, res) => {
  const PObj = require("../models/customer");
  PObj.findByIdAndUpdate(
    req.params.id, /** this 'req.params.id' has to be `_id` value of doc in string format */
    /** internally mongoose will send this as { $set: { prices: req.body.prices }} which will replace `prices` array will new array,
     *  Just in case if you wanted to push new values, have to manually do { $push: { prices: req.body.prices }} each object */
    { prices: req.body.prices },
    { new: true }, /** returns updated doc, this option is not needed if you don't need doc - by default it returns old doc */
    (err, doc) => {
      if (err) {
        console.log("Lookup error: " + err);
        res.status(500).send("Error");
      } else if (doc) { 
        res.status(200).json(task);
      } else { /** `doc` value will be null if no doc is not found for given id */
        res.status(404).send("Something is wrong");
      }
    }
  );
});

参考: .findByIdAndUpdate()