javascript - 如何更新 mongoose 中的数组元素 - MongoDB
问题描述
我正在尝试更新一个MongoDb
集合,其中包含一个名为items
. 我为此目的使用express
和框架。mongoose
这是我的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
which 是一个数组。
//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)
})
推荐阅读
- c# - 即使有明确的等待,Selenium 也会抛出 NoSuchElementException
- spring - Gradle Spring mvc 验证数据类递归 Kotlin
- python - Eventlet heroku flasksocketio 应用程序不工作
- c# - EF Core 播种用户数据在用户表警告中获得重复角色
- c# - 使用 dotnet 和 MsBuild 构建 .NET 应用程序有什么区别?
- node.js - 如何像跟踪 HTTP 请求一样跟踪 gcp pubsub?
- java - 使用 GSON 反序列化 JSON
- c# - c#下载文件给出垃圾响应
- laravel - 如何在没有路径文件的情况下在 Laravel 中获取文件名
- php - 如何被选中