Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 37 ยท CRUD and Queries

Updating Documents in Mongoose

Update data in Mongoose with save(), updateOne, updateMany and findOneAndUpdate; use $set, $inc, $push, upserts, returnDocument and runValidators.

There are two ways to change data in Mongoose, and they behave differently. You can load the document, change it and call save(), or you can send an update operation straight to the database with updateOne, updateMany or findOneAndUpdate. Knowing which to choose is the central skill of this lesson.

Way 1: load, modify, save

JavaScript
const product = await Product.findById(id);
if (!product) throw new Error('Not found');

product.price = 54.9;
product.tags.push('sale');
await product.save();

Advantages: full validation runs, middleware (pre('save')) runs, setters and defaults apply, and you can use your instance methods. Mongoose tracks which paths changed and sends only a $set for those.

Drawbacks: two round trips (read, then write) and a race window: if two requests load the same document, both modify it and both save, the later save overwrites the other's change to the same field. For counters and similar fields prefer atomic operators.

Document#set() and Document#updateOne() also exist: await product.updateOne({ $inc: { views: 1 } }) sends an atomic update for just that document.

Way 2: update operations

These send an update directly; no document is loaded:

JavaScript
await Product.updateOne({ sku: 'KB-100' }, { $set: { price: 44.9 } });
await Product.updateMany({ category: 'peripherals' }, { $inc: { price: 1 } });
await Product.replaceOne({ sku: 'KB-100' }, { sku: 'KB-100', name: 'Keyboard 2', price: 59 });

They return a result object: { acknowledged, matchedCount, modifiedCount, upsertedCount, upsertedId }. matchedCount is how many documents the filter found; modifiedCount is how many actually changed (a document already holding the new value is matched but not modified).

By default these operations do not run document middleware (they run query middleware) and do not run validators unless you ask. Add { runValidators: true }:

JavaScript
await Product.updateOne(
  { sku: 'KB-100' },
  { $set: { price: -5 } },
  { runValidators: true }          // rejects: price below min
);

Note that update validators have quirks: they run only on the paths being updated and this inside custom validators is the query, not a document.

Update operators

Without an operator Mongoose wraps your object in $set for updateOne, but writing the operator makes intent clear.

Operator Effect
$set set field values
$unset remove a field
$inc add to a number (negative to subtract)
$mul multiply a number
$min, $max set only if smaller or larger
$rename rename a field
$currentDate set to the current date
$push append to an array ($each, $position, $slice, $sort modifiers)
$addToSet append if not already present
$pull remove array items matching a condition
$pop remove the first or last array item
$ / $[] / $[id] positional operators for array elements
JavaScript
await Product.updateOne({ _id: id }, {
  $inc: { views: 1 },
  $set: { inStock: true },
  $addToSet: { tags: 'new' },
  $unset: { legacyCode: '' },
});

await Product.updateOne({ _id: id }, { $push: { tags: { $each: ['a', 'b'], $slice: -10 } } });

All fields of one update are applied atomically to that document, so $inc is safe under concurrency.

findOneAndUpdate and findByIdAndUpdate

This finds a document, updates it and returns it, in one atomic operation:

JavaScript
const updated = await Product.findOneAndUpdate(
  { sku: 'KB-100' },
  { $inc: { views: 1 } },
  { returnDocument: 'after', runValidators: true }
);

The most common surprise: by default it returns the document as it was before the update. Use returnDocument: 'after' (or the older new: true) to get the updated one. If nothing matches, the result is null.

Related helpers: findByIdAndUpdate(id, update, options), findOneAndReplace, and findOneAndDelete (in the next lesson).

Upsert

An upsert updates a matching document, or inserts one if none matches:

JavaScript
await Counter.findOneAndUpdate(
  { name: 'visits' },
  { $inc: { value: 1 } },
  { upsert: true, returnDocument: 'after', setDefaultsOnInsert: true }
);

upsert: true makes "create if missing, increment otherwise" a single atomic call, ideal for counters and idempotent syncs. Pair it with a unique index on the filter field so two concurrent upserts cannot create duplicates.

Choosing the method

You want to Use
Run full validation and save hooks load + save()
Change one field safely under concurrency updateOne with $set or $inc
Change many documents updateMany
Get the updated document back findOneAndUpdate with returnDocument: 'after'
Create if missing an upsert

Stand-in: applying update operators

The stand-in below applies $set, $inc, $unset, $push and $addToSet to a plain object, and shows the "returns before or after" difference of findOneAndUpdate. Real MongoDB does this on the server atomically; here it is just object manipulation.

Node.js Update operators (stand-in, not MongoDB)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A race condition, shown

Why does $inc beat load-modify-save? This stand-in simulates two requests that both read a counter and both write back a value.

Node.js Lost update versus atomic increment (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first result is 1: one increment was lost. The atomic approach gives 2.

Common mistakes

  • Forgetting returnDocument: 'after' and receiving the old document.
  • Using updateOne and expecting pre('save') hooks or validators to run.
  • Updating with a plain object that contains _id or immutable fields.
  • Using read-modify-write for counters.
  • Not checking matchedCount (or the null result of findOneAndUpdate) to detect a missing document.
  • Using save() on a lean() object (it has no save).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does findOneAndUpdate return by default?

    Pass returnDocument: 'after' (or new: true) to receive the updated document.
  2. 2. Which approach is safe for incrementing a counter under heavy concurrency?

    $inc is applied atomically inside MongoDB, so concurrent increments are not lost.
  3. 3. Do updateOne and updateMany run validators by default?

    Update operations skip validation unless runValidators is set.
  4. 4. What does upsert: true do?

    Upsert combines update and insert in one atomic operation.

Summary

  • Use load + save() when you need validation, hooks and methods; use updateOne, updateMany or findOneAndUpdate for atomic, single-trip changes.
  • Update operators ($set, $inc, $push, $addToSet, $pull, $unset) change fields atomically.
  • Add runValidators: true and returnDocument: 'after' when needed; upsert creates missing documents.
  • Check matchedCount or null to detect missing targets.

Next: Deleting documents and bulk operations