Sling Academy
Home/Node.js/Understanding the Mongoose Model.updateOne() Function in Node.js

Understanding the Mongoose Model.updateOne() Function in Node.js

Last updated: December 30, 2023

The Model.updateOne() function in Mongoose is a crucial method used to update single documents within the database. This functionality has been part of Mongoose since it introduced the ability to perform update operations on models, following MongoDB’s updateOne operation, which was added in version 3.2 released in December 2015.

The main purpose of updateOne() is to update the first document that matches the given filter in a collection. It’s a shorthand for the standard update operation with the { multi: false } option, ensuring only one document is updated.

Overview

The syntax, parameters, and return value of updateOne().

Syntax:

Model.updateOne(query, update, [options], [callback])

Parameters:

  • query: The selection criteria for the update.
  • update: The modifications to apply.
  • options: Optional settings.
  • callback: Optional callback for executing the query.

The returned value is a promise that resolves to an object containing the outcome of the operation.

Examples

Below are some practical examples of how to use Model.updateOne() in a Node.js application with Mongoose:

Example 1: Basic Update Operation

This example performs a straightforward update on a single document matching specific criteria:

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

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

async function updateLastLogin(username) {
  await User.updateOne(
    { username },
    { $set: { lastLogin: new Date() } }
  );

  console.log('User last login date updated.');
}

await updateLastLogin('johndoe');

This approach is most beneficial when you know that only one document will ever match the criteria, or you only care about the first match being updated.

Example 2: Conditional Upsert

This example demonstrates how to updates a specific field for a document or creates the document if it doesn’t exist:

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

const statusSchema = new Schema({ userId: mongoose.Types.ObjectId, statusText: String });
const Status = mongoose.model('Status', statusSchema);

async function upsertStatus(userId, statusText) {
  await Status.updateOne(
    { userId },
    { $set: { statusText } },
    { upsert: true }
  );

  console.log('Status updated or created.');
}

await upsertStatus(new mongoose.Types.ObjectId('1234567890abcdef4ghijk'), 'Feeling great!');

The use of the upsert option ensures that if no existing document matches the query, a new document will be created using both the query and the update object.

Conclusion

The Mongoose Model.updateOne() function is an essential tool for making single document updates. Its precision and atomicity ensure reliable updates with minimal effort. The above examples provide an understanding of basic usage and more advanced options like upserting. With Mongoose and Node.js, managing document updates can be done efficiently and concisely.

Next Article: Understanding Mongoose Model.deleteOne() Method with Examples

Previous Article: Mongoose Model.findByIdAndRemove() function 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