How to create mongodb bulkWrite update array programmatically?

Hi everyone, I’m trying to update multiple documents in collection by programmatically creating an update array for bulkWrite operation with mongoose.

let updateArr = [];

data.map((position) => {
    position.quantities.map((quantity) => {
    updateArr.push({
        updateOne: {
        filter: {
            _id: mongoose.Types.ObjectId(position.position),
            "quantities._id": mongoose.Types.ObjectId(quantity._id),
        },
        update: {
            $set: {
            "quantity.$.administratorAimedPrice":
                quantity.administratorAimedPrice,
            },
        },
        },
    });
    });
});

console.log(updateArr);

await Position.bulkWrite(updateArr);

This is how the array looks like:

[                                                       
  { updateOne: { filter: [Object], update: [Object] } },
  { updateOne: { filter: [Object], update: [Object] } },
  { updateOne: { filter: [Object], update: [Object] } },
  { updateOne: { filter: [Object], update: [Object] } },
  { updateOne: { filter: [Object], update: [Object] } },
  { updateOne: { filter: [Object], update: [Object] } } 
]

What i’m getting back from mongoose:

POS TypeError: Update document requires atomic operators at OrderedBulkOperation.raw

If there is another way to update multiple documents, with different values by targeting different IDs, please share.

Thank you in advance.

Please close, it’s resolved.

Hi @semperlabs,

Are you able to share the solution to your issue to help others who encounter a similar problem?

Regards,
Stennie

Hi Stennie,
It was just a typo, I had a path “quantities” in the model but I was trying to update “quantity”. It was a long coding sprint so I didn’t see it :slight_smile:

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.