0
0
MongodbHow-ToBeginner · 4 min read

How to Update Document Using Mongoose: Syntax and Examples

To update a document using mongoose, use methods like Model.updateOne(), Model.findByIdAndUpdate(), or Model.updateMany(). These methods take a filter to find the document(s) and an update object with the new values.
📐

Syntax

Here are common methods to update documents in Mongoose:

  • Model.updateOne(filter, update, options): Updates the first document matching the filter.
  • Model.findByIdAndUpdate(id, update, options): Finds a document by its ID and updates it.
  • Model.updateMany(filter, update, options): Updates all documents matching the filter.

The update parameter uses MongoDB update operators like $set to specify fields to change.

javascript
Model.updateOne({ _id: id }, { $set: { field: value } }, options);

Model.findByIdAndUpdate(id, { $set: { field: value } }, options);

Model.updateMany({ status: 'old' }, { $set: { status: 'new' } }, options);
💻

Example

This example shows how to update a user's email by their ID using findByIdAndUpdate. It also returns the updated document.

javascript
const mongoose = require('mongoose');

// Define a simple User schema
const userSchema = new mongoose.Schema({
  name: String,
  email: String
});

const User = mongoose.model('User', userSchema);

async function updateUserEmail(userId, newEmail) {
  await mongoose.connect('mongodb://localhost:27017/testdb');

  const updatedUser = await User.findByIdAndUpdate(
    userId,
    { $set: { email: newEmail } },
    { new: true } // Return the updated document
  );

  console.log('Updated User:', updatedUser);

  await mongoose.disconnect();
}

// Example call (replace 'someUserId' with a real ObjectId string)
updateUserEmail('someUserId', 'newemail@example.com').catch(console.error);
Output
Updated User: { _id: someUserId, name: 'Existing Name', email: 'newemail@example.com', __v: 0 }
⚠️

Common Pitfalls

Common mistakes when updating documents with Mongoose include:

  • Not using $set and accidentally replacing the whole document.
  • Forgetting to set { new: true } option to get the updated document returned.
  • Using updateOne or updateMany without awaiting the promise.
  • Passing an invalid ID format to findByIdAndUpdate.
javascript
/* Wrong: Replaces whole document without $set */
Model.findByIdAndUpdate(id, { email: 'new@example.com' });

/* Right: Uses $set to update only the email field */
Model.findByIdAndUpdate(id, { $set: { email: 'new@example.com' } });
📊

Quick Reference

Here is a quick summary of update methods and options:

MethodDescriptionReturnsCommon Options
updateOne(filter, update, options)Updates first matching documentWrite result{ upsert: true }
updateMany(filter, update, options)Updates all matching documentsWrite result{ upsert: false }
findByIdAndUpdate(id, update, options)Updates document by _idUpdated document{ new: true, runValidators: true }

Key Takeaways

Use update methods like updateOne, updateMany, or findByIdAndUpdate with a filter and update object.
Always use $set to update specific fields without replacing the whole document.
Set { new: true } option to get the updated document returned from findByIdAndUpdate.
Await update calls to ensure the operation completes before proceeding.
Validate IDs and update objects to avoid errors during update.