Sling Academy
Home/Node.js/Mongoose findByIdAndUpdate() function: Tutorial & Examples

Mongoose findByIdAndUpdate() function: Tutorial & Examples

Last updated: December 30, 2023

Introduction

Understanding how to update documents is crucial when working with MongoDB in a Node.js environment. Mongoose, a MongoDB object modeling tool, provides the findByIdAndUpdate() method, streamlining the update process. This tutorial discusses its usage and benefits with clear examples.

Getting Started

To use findByIdAndUpdate(), ensure Mongoose is connected to your MongoDB database:

import mongoose from 'mongoose';
mongoose.connect('mongodb://localhost/my_database');

Defining a Schema and Model

Before using findByIdAndUpdate(), you must have a Mongoose model:

import { Schema, model } from 'mongoose';
const userSchema = new Schema({
  name: String,
  age: Number,
  email: String
});
const User = model('User', userSchema);

Basic Example

The simplest use-case updates a user by ID without options:

const updateUser = async (userId, updateData) => {
  return await User.findByIdAndUpdate(userId, updateData);
};

Options and Their Effects

To customize behavior, pass options such as { new: true } to return the updated document:

const updateUserAndReturnNew = async (userId, updateData) => {
  return await User.findByIdAndUpdate(userId, updateData, { new: true });
};

Handling Errors

Always handle possible errors, especially when the ID is not found:

const updateUserSafely = async (userId, updateData) => {
  try {
    const updatedUser = await User.findByIdAndUpdate(userId, updateData, { new: true });
    return updatedUser || 'User not found.';
  } catch (error) {
    return error.message;
  }
};

Advanced Usage

Updates with Validation

Activate validation with { runValidators: true }:

const updateUserWithValidation = async (userId, updateData) => {
  return await User.findByIdAndUpdate(
    userId,
    updateData,
    { new: true, runValidators: true }
  );
};

Conditional Updates

Include conditions within the update operation using query operators:

const conditionalUpdateUser = async (userId, updateData) => {
  return await User.findOneAndUpdate(
    { _id: userId, age: { $lt: 30 } },
    updateData,
    { new: true }
  );
};

Using Update Operators

Use MongoDB update operators such as $inc to increment field values:

const incrementUserAge = async (userId) => {
  return await User.findByIdAndUpdate(
    userId,
    { $inc: { age: 1 } },
    { new: true }
  );
};

Conclusion

Mongoose’s findByIdAndUpdate() provides an efficient way to update documents. Always remember to handle conditions and validation to ensure data integrity. The transition from callbacks to modern async/await in Node.js enhances readability and error handling in your CRUD operations.

Next Article: Understanding the Map schema type in Mongoose

Previous Article: Virtuals in Mongoose: Explained with Examples

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates