Return newly upserted document using findOneAndUpdate

I am using mongodb native driver for Node.js and I recently updated mongodb version from 3 to 4. I am using mongodb npm package.
Due to migration, I had to change a lot of queries due to changes in insertOne query and findOneAndUpdate query. Before insertOne returned ops object that contained newly inserted document fields, and similarly for insert/update queries such as findOneAndUpdate, I was getting updated/upserted document using the following options configuration

const options = { upsert: true, returnOriginal: false }

ever since I migrated to version 4, findOneAndUpdate on upsert does not return the newly upserted document as demonstrated below

Upsert

{
  lastErrorObject: {
    n: 1,
    updatedExisting: false,
    upserted: new ObjectId("ID")
  },
  value: null,
  ok: 1
}

Update (same query on upserted document)

{
  lastErrorObject: { n: 1, updatedExisting: true },
  value: {
    _id: new ObjectId("ID"),
    userId: 'userId',
    items: [ [Object] ]
  },
  ok: 1
}

and I used the following options configuration

const options = {
    upsert: true,
    returnNewDocument: true,
};

Is there any way to return upserted document using findOneAndUpdate or do I have to call findOne query after upsert operation in order to send document to client-side.
Update/Insert query cannot be changed due to the nature of business logic, any help will be appreciated!

1 Like