Skip to main content

How to insert unique object to Mongo Db or update it

I have a task to insert array of objects to mongo db collection. If the collection already has the record with same key parameters - update the values (if not - insert). My object look like this:

{
  keyParameter: 'value',
  keyForUpdate1: 'someValue1',
  keyForUpdate2: 'someValue2',
  keyForUpdateN: 'someValueN',
}

I try to do following code:

 dataStore.collectionName.bulkWrite(
      myArray.map((item) => ({
        updateOne: {
          filter: {
            keyParameter: item.keyParameter,
          },
          update: {
            $set: {
              keyForUpdate1: item.keyForUpdate1,
              keyForUpdate2: item.keyForUpdate2,
              keyForUpdateN: item.keyForUpdateN
            },
            $setOnInsert: {
             keyParameter: item.keyParameter,
            },
          },
          upsert: true
        }
      }))

Now it doesn't work. First time it record array two times. After insert, but not update. What I do wrong and how to reach my goal?

Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Comments