如何更新猫鼬中的数组元素
我正在尝试更新一个名为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
。
//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)
})
如何更新猫鼬中的数组元素
我正在尝试更新一个名为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
。
//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)
})