What is replaceOne() in Mongoose?

In MongoDB, and when using Mongoose, you may want to update a document at times. This can be done with just the update() method. However, you may also want to replace the document. This is where the replaceOne() method comes in. replaceOne() does not require any atomic operator like $set. Based on the filter specified, it matches the document found, and replaces it with the one given.

Syntax

query.replaceOne(filter, newDcoument)

Parameters

filter: This is an object that specifies the path or field to match in the documents of a collection.

newDocument: This is the new document to replace the one found.

Return value

A query result is returned using this method. The query result is a write result which contains information such as number of documents matched, number of documents modified, and a Boolean that indicates if the action was successful.

Example

In the example below, we demonstrate the use of replaceOne() method. We created a product schema using Mongoose, and made a query together with replaceOne(). The customer with the filter is matched and is replaced with the given document.

// import mongoose
const mongoose = require("mongoose");
// creating a product Schema with mongoose
let Product = mongoose.model("Item", new mongoose.Schema({
name: String,
category: Number,
price: Number,
tag: String
})
)
// make use of the `replaceOne()` method
let product = await Product.replaceOne({name: "Cadabra"}, {name : "Amazon"});

When the product result returned is logged to the console, the matchedCount is the number of documents matched. modifiedCount is the number of documents modified.

Free Resources