Lahiru Madusanka
Lahiru Madusanka

Reputation: 63

How to update Array Element in mongoose - MongoDB

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.

Upvotes: 1

Views: 168

Answers (2)

Seneca Manu
Seneca Manu

Reputation: 56

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) { ... })

Upvotes: 0

Subburaj
Subburaj

Reputation: 5192

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)
    })

Upvotes: 1

Related Questions