Mongoose replaceOne() function: Tutorial & Examples

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

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.