Home > Software engineering >  Throw an error if update operation did not suceed
Throw an error if update operation did not suceed

Time:10-27

I have following update logic for one of my collections

  async update(uid, data, version) {
    const filter = { _id: new ObjectId(uid), version }
    const update = { $set: data, $inc: { version: 1 } }
    const result = await myCollection.updateOne(filter, update)

    if (!result.acknowledged) {
      throw new Error('Errored')
    }
  },

Idea here is to update document only if it matches provided version, however after few experiments with invalid version I am unable to get this function to throw an error.

I get following results for invalid request

{
  acknowledged: true,
  modifiedCount: 0,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 0
}

and following for valid request

{
  acknowledged: true,
  modifiedCount: 1,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 1
}

I was expecting mongo to throw an error or return acknowledged: false if update was not possible. Is the only way to throw here a check for modifiedCount: 0? Or am I missing some settings / using incorrect action?

CodePudding user response:

I'm not entirely familiar with mongodb, but an example I found in the documentation shows that if no matches are found, the operation can return acknowledged: true So you have to check if matchedCount and modifiedCount are 0.

  • Related