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

Mongoose replaceOne() function: Tutorial & Examples

Last updated: December 30, 2023

Introduction

The replaceOne() function in Mongoose is a powerful method used to replace a single document in a collection matching the given filter with a new document. This function provides a way to perform a full document replacement in MongoDB, which differs from updating field values with updateOne() or other update methods. In this article, we will explore the usage of replaceOne() with examples.

The replaceOne() method was introduced in Mongoose version 4.x, following the MongoDB server’s addition of the replaceOne operation in version 3.2, released in December 2015 (almost a decade ago).

The primary usage of replaceOne() is to completely replace an existing document with a new one rather than updating particular fields. This operation can be particularly useful when document structures change significantly, and field-level updates are not practical.

Syntax

Model.replaceOne(filter, replacement, [options], [callback])

Parameters:

  • filter: The filter object used to select the document to replace.
  • replacement: The new document that will replace the selected document.
  • options (optional): Additional options such as upsert which can create a new document if no documents match the filter.
  • callback (optional): A function to call when the operation completes. If not provided, the method returns a promise.

A promise resolving to the result object if no callback is provided. The result object contains information like matchedCount, modifiedCount, and upsertedId if applicable.

Code Examples

Replacing a User Document

Replace an existing user document matching a given username with a new document containing updated information.

import mongoose from 'mongoose';
import { User } from './models/user.js';

const replaceUserDocument = async (username, newUser) => {
  try {
    const result = await User.replaceOne({ username }, newUser);
    console.log('Replace Result:', result);
  } catch (error) {
    console.error('Error replacing the user document:', error);
  }
};

// Usage: Replacing a user with username 'jdoe'
const updatedUser = {
  username: 'jdoe',
  email: '[email protected]',
  age: 30
};

await replaceUserDocument('jdoe', updatedUser);

Using upsert Option

Replace a document and use the upsert option to create a new document if no existing document matches the filter.

import mongoose from 'mongoose';
import { Product } from './models/product.js';

const replaceOrInsertProduct = async (productId, newProduct) => {
  try {
    const options = { upsert: true };
    const result = await Product.replaceOne({ _id: productId }, newProduct, options);
    console.log('Upsert Result:', result);
  } catch (error) {
    console.error('Error with upsert operation:', error);
  }
};

// Usage: Replacing/Inserting a product
const newProductDetails = {
  _id: productId,
  name: 'New Product',
  price: 19.99
};

await replaceOrInsertProduct(mongoose.Types.ObjectId('some-product-id'), newProductDetails);

Conclusion

In conclusion, the replaceOne() function in Mongoose is a valuable tool for cases where you need to perform a full document replacement in your MongoDB collections. By understanding its usage, syntax, and options, developers can effectively manage data transformations that are more radical than simple updates, ensuring data integrity and consistency in the application’s database.

Next Article: Using the Mongoose Model.find() function (with examples)

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