【问题标题】:Mongoose - replace all array elementsMongoose - 替换所有数组元素
【发布时间】:2020-04-27 02:22:11
【问题描述】:

我想替换 'prices' 中的所有数组元素,如下所示:

{
 "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 中没有任何更改。请帮助我更正我的代码。感谢!

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案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()

    【讨论】:

    • 那是我疯狂的错。我没有在模式中定义“价格”。谢谢@whoami
    猜你喜欢
    • 1970-01-01
    • 2015-12-09
    • 2015-03-27
    • 2021-12-24
    • 2018-12-21
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 2016-11-11
    相关资源
    最近更新 更多