0

Consider the following collection of documents with an array of documents inside:

PurchaseOrder {
   id: '5b675d8180db9c13ac5b5c16',
   productItems: [
      { 
          quantity: 10,
          discount_id: '5af6452dcab5ce0ee2d47e63'
      },
      { 
          quantity: 10,
          discount_id: '5af6452dcab5ce0ee2d47e66'
      },
      { 
          quantity: 12,
          discount_id: null
      },
      { 
          quantity: 9,
          discount_id: '5af6452dcab5ce0ee2d47e63'
      },
      { 
          quantity: 7,
          discount_id: '5af6452dcab5ce0ee2d47e66'
      },
      { 
          quantity: 3,
          discount_id: null
      },
      { 
          quantity: 5,
          discount_id: '5af6452dcab5ce0ee2d47e66'
      }
   ]
}

I need to update, programatically using mongoose, for all collection, all discount_id's where discount_id equals certain id (example: 5af6452dcab5ce0ee2d47e63).

Here is my try:

let selectedDiscount = {
   _id: '5af6452dcab5ce0ee2d47e63'
}

PurchaseOrderModel.update(
        {},
        { $set: { "productItems.$[item].discount_id": null } },
        {
            multi: true,
            arrayFilters: [{ "item.discount_id": selectedDiscount._id }]
        }
    );

Unfortunatelly I'm getting an error Can't use $set with the above statement.

How can I achieve such an operation in a single mongoose call ?

Mendes
  • 17,489
  • 35
  • 150
  • 263

0 Answers0