How to Use findOneAndUpdate() in Mongoose

Sponsor #native_company# — #native_desc#

The findOneAndUpdate() function in Mongoose has a wide variety of use cases. You should use save() to update documents where possible, but there are some cases where you need to use findOneAndUpdate(). In this tutorial, you’ll see how to use findOneAndUpdate(), and learn when you need to use it.

Getting Started

As the name implies, findOneAndUpdate() finds the first document that matches a given filter, applies an update, and returns the document. By default, findOneAndUpdate() returns the document as it was before update was applied.

  1. const Character = mongoose.model('Character', new mongoose.Schema({
  2. name: String,
  3. age: Number
  4. }));
  5. await Character.create({ name: 'Jean-Luc Picard' });
  6. const filter = { name: 'Jean-Luc Picard' };
  7. const update = { age: 59 };
  8. // `doc` is the document _before_ `update` was applied
  9. let doc = await Character.findOneAndUpdate(filter, update);
  10. doc.name; // 'Jean-Luc Picard'
  11. doc.age; // undefined
  12. doc = await Character.findOne(filter);
  13. doc.age; // 59

You should set the new option to true to return the document after update was applied.

  1. const filter = { name: 'Jean-Luc Picard' };
  2. const update = { age: 59 };
  3. // `doc` is the document _after_ `update` was applied because of
  4. // `new: true`
  5. let doc = await Character.findOneAndUpdate(filter, update, {
  6. new: true
  7. });
  8. doc.name; // 'Jean-Luc Picard'
  9. doc.age; // 59

Mongoose’s findOneAndUpdate() is slightly different from the MongoDB Node.js driver’s findOneAndUpdate() because it returns the document itself, not a result object.

As an alternative to the new option, you can also use the returnOriginal option. returnOriginal: false is equivalent to new: true. The returnOriginal option exists for consistency with the the MongoDB Node.js driver’s findOneAndUpdate(), which has the same option.

  1. const filter = { name: 'Jean-Luc Picard' };
  2. const update = { age: 59 };
  3. // `doc` is the document _after_ `update` was applied because of
  4. // `returnOriginal: false`
  5. let doc = await Character.findOneAndUpdate(filter, update, {
  6. returnOriginal: false
  7. });
  8. doc.name; // 'Jean-Luc Picard'
  9. doc.age; // 59

Atomic Updates

With the exception of an unindexed upsert, findOneAndUpdate() is atomic. That means you can assume the document doesn’t change between when MongoDB finds the document and when it updates the document, unless you’re doing an upsert.

For example, if you’re using save() to update a document, the document can change in MongoDB in between when you load the document using findOne() and when you save the document using save() as show below. For many use cases, the save() race condition is a non-issue. But you can work around it with findOneAndUpdate() (or transactions) if you need to.

  1. const filter = { name: 'Jean-Luc Picard' };
  2. const update = { age: 59 };
  3. let doc = await Character.findOne({ name: 'Jean-Luc Picard' });
  4. // Document changed in MongoDB, but not in Mongoose
  5. await Character.updateOne(filter, { name: 'Will Riker' });
  6. // This will update `doc` age to `59`, even though the doc changed.
  7. doc.age = 59;
  8. await doc.save();
  9. doc = await Character.findOne();
  10. doc.name; // Will Riker
  11. doc.age; // 59

Upsert

Using the upsert option, you can use findOneAndUpdate() as a find-and-upsert operation. An upsert behaves like a normal findOneAndUpdate() if it finds a document that matches filter. But, if no document matches filter, MongoDB will insert one by combining filter and update as shown below.

  1. const filter = { name: 'Will Riker' };
  2. const update = { age: 29 };
  3. await Character.countDocuments(filter); // 0
  4. let doc = await Character.findOneAndUpdate(filter, update, {
  5. new: true,
  6. upsert: true // Make this update into an upsert
  7. });
  8. doc.name; // Will Riker
  9. doc.age; // 29

The `rawResult` Option

Mongoose transforms the result of findOneAndUpdate() by default: it returns the updated document. That makes it difficult to check whether a document was upserted or not. In order to get the updated document and check whether MongoDB upserted a new document in the same operation, you can set the rawResult flag to make Mongoose return the raw result from MongoDB.

  1. const filter = { name: 'Will Riker' };
  2. const update = { age: 29 };
  3. await Character.countDocuments(filter); // 0
  4. let res = await Character.findOneAndUpdate(filter, update, {
  5. new: true,
  6. upsert: true,
  7. rawResult: true // Return the raw result from the MongoDB driver
  8. });
  9. res.value instanceof Character; // true
  10. // The below property will be `false` if MongoDB upserted a new
  11. // document, and `true` if MongoDB updated an existing object.
  12. res.lastErrorObject.updatedExisting; // false

Here’s what the res object from the above example looks like:

  1. { lastErrorObject:
  2. { n: 1,
  3. updatedExisting: false,
  4. upserted: 5e6a9e5ec6e44398ae2ac16a },
  5. value:
  6. { _id: 5e6a9e5ec6e44398ae2ac16a,
  7. name: 'Will Riker',
  8. __v: 0,
  9. age: 29 },
  10. ok: 1 }