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.
-
You should consider i more dynamic approach. This approach will set the fields that are not sent in the request to null. Take a look at array filters as well docs.mongodb.com/manual/reference/operator/update/…O'Dane Brissett– O'Dane Brissett2019年10月04日 14:23:51 +00:00Commented Oct 4, 2019 at 14:23
2 Answers 2
You can do with update straightforward as follows:
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)
})
5 Comments
qty which is I don't want."items._id": "Id of item for which user needs to update" based on the condition for a particular itemitem_id ?$set:{items:"constructed array"}On mongoose, there is a '$' that indicates an array, and you can do this:
invoicesDB.update({_id: req.params.id}, {'$set': {
'items.$.itemID': 'Here is where you update',
}}, function(err) { ... })
Comments
Explore related questions
See similar questions with these tags.