Sling Academy
Home/Node.js/[Solved] Mongoose: findOneAndUpdate Not returning updated document

[Solved] Mongoose: findOneAndUpdate Not returning updated document

Last updated: December 30, 2023

Understanding the findOneAndUpdate Issue

When using the findOneAndUpdate function with Mongoose, it is commonly expected that the operation returns the modified document. However, by default, this function will return the original document that was found before the update was applied. This is often a point of confusion and can lead to unexpected behavior if you’re not aware of the default settings. When developers encounter this, they typically haven’t specified that they want the updated document to be returned.

Solutions

Specifying the Return of the Updated Document

To ensure findOneAndUpdate returns the updated document, we need to set the new option to true. This tells Mongoose to return the modified version of the document rather than the original. Below is a code example demonstrating how you can ensure that your findOneAndUpdate calls return the updated document:

import mongoose from 'mongoose';
const { Schema } = mongoose;

const YourSchema = new Schema({ /* your schema fields */ });
const YourModel = mongoose.model('YourModel', YourSchema);

const query = { /* query criteria */ };
const update = { $set: { /* updated fields */ } };
const options = { new: true };

YourModel.findOneAndUpdate(query, update, options)
  .then(updatedDocument => {
    // Handle the updated document
  })
  .catch(error => {
    // Handle the error
  });

Considering the useFindAndModify Global Option

Beyond the new option, it’s essential to know that as of Mongoose 5.0, findOneAndUpdate() uses MongoDB’s findAndModify() engine by default, which is deprecated. To avoid deprecation warnings and use the findOneAndUpdate function without any issues, you should set the useFindAndModify flag to false globally when connecting to MongoDB. Here is how you do it:

mongoose.connect('yourMongoDBUri', { useFindAndModify: false });

This configuration change helps promote best practices and ensures your codebase is prepared for future compatibility.

Next Article: Fixing Mongoose CastError: Cast to ObjectId failed

Previous Article: Mongoose: Defining a schema with nested objects

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