Mongoose updateMany() function explained (with examples)

Updated: December 30, 2023 By: Guest Contributor Post a comment

A Brief Overview

Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and translates between objects in code and their representation in MongoDB. One of its powerful features is the updateMany() function. This function was incorporated into Mongoose following its initial release, evolving with the library to include promises and async/await which is a part of ECMAScript 2017 (ES8).

The main use of the updateMany() function is to update all documents that match the given filter in a collection. Instead of updating a single document, it provides a way to update multiple documents in bulk with a specified update operation.

Syntax and Parameters

Model.updateMany(filter, update, options, callback) // with callback
Model.updateMany(filter, update, options) // returns a Query which can be then-able
  • filter: The search criteria to determine which documents to update.
  • update: The modifications to apply.
  • options: (Optional) Options like upsert, writeConcern, collation, etc.
  • callback: (Optional) A function to run upon completion of the update.

The function returns a promise if no callback is provided. It also returns an object containing various metadata such as matchedCount, modifiedCount, etc.

Examples

Updating User Roles

This example demonstrates updating user roles from ‘guest’ to ‘member’ in a user collection.

const mongoose = require('mongoose');
const { Schema } = mongoose;

const userSchema = new Schema({ username: String, role: String });
const User = mongoose.model('User', userSchema);

async function updateRoles() {
  try {
    await mongoose.connect('mongodb://localhost:27017/test');
    const result = await User.updateMany({ role: 'guest' }, { $set: { role: 'member' } });
    console.log(result);
  } catch (error) {
    console.error(error);
  } finally {
    await mongoose.disconnect();
  }
}

updateRoles();

Setting Account Expiration

This example sets an expiration date on accounts that are currently labeled as ‘trial’.

// Continuing with the User model from the previous example

async function setAccountExpiration() {
  try {
    await mongoose.connect('mongodb://localhost:27017/test');
    const expirationDate = new Date();
    expirationDate.setDate(expirationDate.getDate() + 30);
    const result = await User.updateMany({ role: 'trial' }, { $set: { accountExpiration: expirationDate } });
    console.log(result);
  } catch (error) {
    console.error(error);
  } finally {
    await mongoose.disconnect();
  }
}

setAccountExpiration();

Conclusion

The updateMany() method in Mongoose is a robust tool for managing bulk document updates. Whether you’re setting user roles, updating statuses, or modifying data en masse, understanding how to use updateMany() can make your Node.js and MongoDB applications more efficient. As with any powerful feature, ensure you use it with caution to prevent unintended data changes. By leveraging modern JavaScript features like async/await, managing databases with Node.js and Mongoose becomes a more streamlined and pleasant experience.