MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

Calling findOneAndUpdate with a returnNewDocument projection returns a date that is different than the one saved to the database

Problem:

When I call this function in my code, occasionally I’ll get a slightly different date back in the projection from the database compared to the one that findOneAndUpdate has stored in it. They are only different by one or two milliseconds but it means that I can’t rely on the value to make future comparisons between the client state and the current database state.

Environment Details:

  • Client SDK: “mongodb-stitch-browser-sdk”: “^4.8.0”
  • MongoDB Atlas Version 4.2.6 Region N.Virginia(us - east - 1) Cluster Tier M0 Sandbox(General)

Example Results:

  • Saved In Database Value: 2020-05-04T18:28:32.271+00:00
  • Returned In Projection Value: 2020-05-04T18:28:32.270Z <— different by one millisecond!

My Code (Within a Vue / Vuex framework setting):

export async function setSubscriptionAction (context, payload) {

  const query = {
    user_id: Stitch.defaultAppClient.auth.user.id,
    'communication.subscriptions.lastModified': context.state.communication.subscriptions.lastModified
  }

  const update = {
    $set: {
      'communication.subscriptions.newsletter': payload.newsletter
    },
    $currentDate: {
      'communication.subscriptions.lastModified': true
    }
  }

  const options = {
    returnNewDocument: true,
    projection: {
      communication: {
        subscriptions: {
          lastModified: 1
        }
      }
    }
  }

  const result = await this._vm.$atlasServiceClient.db(DB_ACCOUNT_OWNER).collection(COLLECTION_ACCOUNT).findOneAndUpdate(query, update, options)

  if (!result) {
    throw new Error('APP_NEWER_LAST_MODIFIED_FOUND')
  }

  payload.lastModified = result.communication.subscriptions.lastModified

  context.commit(SET_SUBSCRIPTIONS_MUTATION, payload)

Is there something I’ve missed? Thanks!