1

I post this question in relation to my use case.

It is true that there is a lot of response in the same subject but I do not find an answer .

that is why I ask you for help Thanks.

I would like to be able to update the lineItemStatus inside lineItems array.

Here is my model :

const orderSchema = new Schema(
 lineItems: [{
   lineItemStatus: {
    type: String,
    default: 'en waiting for validation',
    lowercase: true
    }
  }]
)

The result look like this

{
  "_id": "5c659cd0be79c124126d5ec2",
  "lineItems": [{
        "lineItemStatus": "waiting for validation", //the status to update
        "_id": "1"
    },
    {
        "lineItemStatus": "delivered",
        "_id": "2"
    }
 ]
}

First I'm able to get a single item of lineItems. this is the code

async updateStatus(req, res) {
  let givenLineItemId = req.body.lineItemId
  let givenlineItemStatus = req.body.status // the status to update

  try {
    const ObjectId = mongoose.Types.ObjectId
    const aggregationStages = [
     {
       $unwind: '$lineItems'
     },
     {
       $match: {
         'lineItems._id': ObjectId(givenLineItemId)
       }
     }
    ]

   await Order
     .aggregate(aggregationStages)
     .exec(function(err, orders) {
     if (err) res.status(400).send(err)
     res.status(200).send(orders)
   })
   } catch (err) {
     return res.status(500).send(err)
   }
}

But now i'm not able to to update the lineItemStatus i see some way to use set or push but it doesn't work.

Thanks a lot for the help.

Birante
  • 689
  • 5
  • 15

1 Answers1

1

The aggregation stage itself does not support updates. You have two options:

1) Collect the aggregate results into a variable and do a bulk update. See link.

2) Call forEach on the aggregate. You can see samples provided in this answer.

Bajal
  • 5,487
  • 3
  • 20
  • 25