Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Updating Documents | CRUD Operations with Mongoose
MongoDB and Mongoose Essentials

Updating Documents

Свайпніть щоб показати меню

Updating documents in MongoDB with Mongoose can be done in several ways, each suited for different scenarios. Here is a code example that demonstrates three common methods: updateOne(), updateMany(), and findByIdAndUpdate().

// Assume you have a Mongoose model called User

// 1. updateOne(): Update the first matching document
User.updateOne(
  { email: "alice@example.com" }, // Filter: find user by email
  { $set: { isActive: true } } // Update operator: set isActive to true
).then((result) => {
  console.log("updateOne result:", result);
});

// 2. updateMany(): Update all matching documents
User.updateMany(
  { role: "subscriber" }, // Filter: all users with role 'subscriber'
  { $inc: { loginCount: 1 } } // Update operator: increment loginCount by 1
).then((result) => {
  console.log("updateMany result:", result);
});

// 3. findByIdAndUpdate(): Find a document by its ID and update it
User.findByIdAndUpdate(
  "60f7c2d5e1b1c8abc1234567", // The document's _id
  { $set: { lastLogin: new Date() } }, // Update operator: set lastLogin to now
  { new: true, runValidators: true } // Options: return updated doc, run validators
).then((updatedUser) => {
  console.log("findByIdAndUpdate result:", updatedUser);
});

Each method accepts a filter to select documents, an update object (often using update operators like $set or $inc), and optional settings.

When updating documents with Mongoose, you use update operators to specify how fields should be changed. Common operators include '$set' to assign a new value, '$inc' to increment a number, and '$unset' to remove a field.

You can also pass options to these update methods. For example, the { new: true } option in findByIdAndUpdate() returns the updated document instead of the original. The { runValidators: true } option ensures that schema validation rules are applied during the update.

There are two main approaches to updating documents:

  • Direct updates: methods like updateOne(), updateMany(), and findByIdAndUpdate() send the update directly to MongoDB. These methods do not load the whole document into memory and do not trigger middleware hooks like save(). They are efficient for bulk or targeted updates but may bypass custom logic in your schema;
  • Document modification followed by save(): alternatively, you can first retrieve a document, modify its properties in your code, and then call save(). This approach loads the full document, lets you use instance methods, and runs all middleware hooks. It is useful when you need custom logic or want to trigger pre or post hooks.

Choosing between these approaches depends on your needs for efficiency, validation, and schema logic. The code example above illustrates direct update methods, which are concise and performant for many common update operations.

question mark

Which statement best describes the difference between using updateOne() and modifying a document followed by save() in Mongoose?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 3

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 3. Розділ 3
some-alt