Home > other >  using updateOne inside a map, setting the filter to the unique id , $set is to the document and upse
using updateOne inside a map, setting the filter to the unique id , $set is to the document and upse

Time:10-31

enter image description here

here is my code in the controller from where i am getting the records from my google calendar API and then passing that data to this function and the code inside the function which inserts the document (records) looks like this as below:

Holiday.bulkWrite(
    holidays.map((holiday) => ({
        updateOne: {
            filter: { holidayId: holiday.id },
            update: { $set: holiday },
            upsert: true,
        },
    }))
)

CodePudding user response:

It's hard to tell what exactly the issue is because it is not Mongo related but code related, from what it seems you are just using the wrong field for the filter.

holiday.id is null, and we can see that the "inserted" documents do not have such field. You are basically executing the following update:

db.collection.update({
  holidayId: null
},
{
  "$set": {
    holidayId: "123"
    ... other fields
  }
},
{
  "upsert": true
})

I believe this simple fix would solve your issue, change .id To .holidayId:

Holiday.bulkWrite(
    holidays.map((holiday) => ({
        updateOne: {
            filter: { holidayId: holiday.holidayId },
            update: { $set: holiday },
            upsert: true,
        },
    }))
)
  • Related