0

I have an object user that looks like that

{
    "_id" : ObjectId("5edbdf57ac52325464b054ec"),
    ...
    "purchaseHistory" : [ 
        {
            "_id" : ObjectId("5ee7a8f6b438a1254cec3f74"),
        ...
        },
        {
            "_id" : ObjectId("5ee7a8f6b438a1254cec3f88"),
        ...
        }
    ]
}

What I wanna do is to add a new field to a specific object inside "purchaseHistory" by ID, for example I wanna add to "5ee7a8f6b438a1254cec3f88" a field "status": 0

What I tried is

users.findOneAndUpdate(
    {
        _id: ObjectId(userId),
        'purchaseHistory._id': ObjectId(saleId)
    },
    {
        $set: { 'purchaseHistory.$.status': status}
    }
)

But it gives me an error, how can I do it properly?

daniel93
  • 181
  • 1
  • 12

2 Answers2

0

According to the website provided by D. SM, I was able to do it this way

users.findOneAndUpdate(
    {
        '_id': ObjectId(userId),
        'purchaseHistory._id': ObjectId(saleId)
    },
    {
        $set: { 'purchaseHistory.$.status': status }
    }
)
daniel93
  • 181
  • 1
  • 12
-1

MongoDB provides the positional update operator for cases like this.

D. SM
  • 13,584
  • 3
  • 12
  • 21