Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

mongoose
mongodb
communitycreator

What is replaceOne() in Mongoose?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

mongoose
mongodb
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring