Updating two seperate documents using bulkWrite() with the MongoDB Node.js Driver

Greetings! I am currently stuck with this issue. I’m trying to update two different documents. Normally, I’d use updateMany() but the catch is that they should receive different values as well. I would have just nested two updateOne() functions instead but I’m afraid that if the database somehow becomes unavailable during the request and the first updateOne() function gets executed and the second does not, a mess will happen. That’s why I am looking for a way to update two individual documents with two different values, at once. I looked through the forums for a solution and stumbled across the bulkWrite() function. I tried it and it actually only updates the last document I have specified. As I said, I’m trying to update two documents. The first one seems to be ignored, while the second and last one gets executed just the way I want. Why does that occur? And would that even be a solution to my problem?

dbo.collection("ids").bulkWrite([{ updateOne: { "filter": { _id: // ... }, "update": { $set: { contacts: people[0] } } }, updateOne: { "filter": { _id: // ... }, "update": { $set: { contacts: people[1] } } } }], function(error, answer) { // ... }

I have tried switching the two different filters for the updateOne() functions and the second one took effect, while the first one didn’t. This proves that the problem doesn’t come from the filters themselves. I also tried updating other fields, in order to make sure the problem doesn’t come from what’s being set. It didn’t make any difference.

Any kind of help would be appreciated!

You are describing a transaction
See https://docs.mongodb.com/manual/core/transactions/

2 Likes

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