javascript - 如何更新 Mongoose 中的数组元素 - MongoDB

标签 javascript node.js mongodb express mongoose

我正在尝试更新一个 MongoDb 集合,它有一个名为 items文档数组。为此,我正在使用 expressmongoose 框架。

这是我的schema 的样子:

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

let invoices = new Schema({
  vendor: { type: String },
  invoiceDate: { type: Date, default: Date.now },
  expectedDate: { type: Date, default: Date.now },
  billingAddress: { type: String },
  contactPerson: { type: String },
  items: [
    {
      itemID: Schema.Types.ObjectId,
      qty: { type: Number },
      unitPrice: { type: Number },
      linePrice: { type: Number }
    }
  ],
  totalPrice: { type: Number }
});

module.exports = mongoose.model("invoices", invoices);

我想通过首先找到特定文档的 id 来更新某个文档,然后相应地更新 items

这是我到目前为止尝试过的方法,我不知道下一步该去哪里更新 items,它是一个数组。

//end-point-4
Routes.route('/update/:id').post((req, res) => {
    invoicesDB.findById(req.params.id, (err, invoice) => {
        if(!invoice){
            res.status(404).send('Not found!');
        }else{
            invoice.vendor = req.body.vendor;
            invoice.invoiceDate = req.body.invoiceDate;
            invoice.expectedDate = req.body.expectedDate;
            invoice.billingAddress = req.body.billingAddress;
            invoice.contactPerson = req.body.contactPerson;

            //how to update items
            invoice.items = req.body.items; //this I guess, gives the answer but not sure.

            invoice.totalPrice = req.body.totalPrice;
        }
    });
});

PS:我不想更新items中的某一项。我想要的是用给定的值更新数组中的每个项目。

举个例子,假设用户只想更新 items 中的特定项目,因此应该只更新该特定项目。

最佳答案

您可以按如下方式直接更新:

    invoicesDB.update(
      { "_id" : :req.params.id, “items._id": “Id of item for which
                                  user needs to update” }, 
      { "$set": { “items.$.qty”: 5}}, 
      function(err, company) {
        console.log(company)
    })

关于javascript - 如何更新 Mongoose 中的数组元素 - MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58229639/

相关文章:

javascript - 获取未加载的元素

javascript - Jgrid 单击按钮保存单元格

javascript - 警报未出现在本地主机中

javascript - 返回 null mysql nodejs

node.js - 安装 node.js 6.3.1 - 没有这样的文件或目录

javascript - 使用 ibm_db 模块在 Node JS 中执行准备好的语句时出现问题

java - mongodb BSON对象错误

mongodb - 如何在 hostgator VPS 中安装 mongodb 扩展?

javascript,又一个 TypeError : 'undefined' is not a function

mongodb - 综合平均值