1

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.

1

2 Answers 2

1

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)
    })
Sign up to request clarification or add additional context in comments.

5 Comments

This will update the every item with that qty which is I don't want.
@Lahiru Madusanka it wont update all items it will update “items._id": “Id of item for which user needs to update” based on the condition for a particular item
So I have like many items. say 10. So I need to update each and every item. How can I achieve this? Should I write this end point to run 10 times (using a loop) for each item_id ?
If you want to update 10 items, in one shot construct the array and user straightly` $set:{items:"constructed array"}
I don't get it. So how the items will be updated with their unique id if they are given with a constructed array? Can you give an example?
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.