I am trying to update a MongoDb collection which has an array of document named items. I am using express and mongoose frameworks for this purpose.
Here is how my schema looks like:
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);
I want to update a certain document by first finding the id of that particular document and then update items accordingly.
This is what I tried so far and I don't know where to go next on updating the items which is an array.
//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: I don't want to update a certain item in the items. What I want is to update the every item in the array with the given value.
For an example let's say the user only wants to update a particular item in the items, so only that particular item should be updated.