mongoose replaceOne

Introduction

The CRUD update operation is one that should be handled with the utmost care. The update operation modifies the data in a database. Even a small mistake can create many problems. So, the update operations should be performed carefully. Data in MongoDB can be updated using various methods. There are several methods that are available in mongoose such as updateOne(), update(), and updateMany(). These methods modify a single or more document. But there is one more method known as replaceOne(). This method is also used for updating documents. Unlike other update methods, the replaceOne() method does not update the values of documents, instead, it replaces a document with a whole new document. In this article, we will discuss how to use replaceOne() in mongoose.

We will use the replaceOne() method on the kennel collection.

{ "_id" : ObjectId("5df390ce4e8d7e9979b2d21d"), "name" : "Rambo", "age" : 5, "breed" : "Pitbull" }
{ "_id" : ObjectId("5df390f34e8d7e9979b2d21e"), "name" : "Scooby Doo", "age" : 2, "breed" : "Great Dane" }
{ "_id" : ObjectId("5df391034e8d7e9979b2d21f"), "name" : "Romeo", "age" : 3, "breed" : "German Shephard" }
{ "_id" : ObjectId("5df391404e8d7e9979b2d220"), "name" : "Spike", "age" : 3, "breed" : "Pitbull" }
{ "_id" : ObjectId("5df391544e8d7e9979b2d221"), "name" : "Lui", "age" : 2, "breed" : "Pugg" }

For performing HTTP endpoint testing, we will use the postman tool. You can download the postman tool from www.getpostman.com.

replaceOne()

As the name suggests, the replaceOne() methods replace a single document with a new document. We need to pass a query, and the document to be replaced will be replaced according to it.

The following route handler will be invoked when the endpoint ‘replace’ will be executed.

router.route("/replace").put(function(req, res) {});

The replaceOne() method has three parameters – a query, a new document, and a callback function. The callback function, in turn, has two parameters – an error and the result. So let’s use the replaceOne() method on the kennel collection.

router.route("/replace").put(function(req, res) {
  kennel.replaceOne(
    { name: "Romeo" },
    { name: "Johnny Boy", age: 2, breed: "Labrador" },
    function(err, result) {
      if (err) {
        res.send(err);
      } else {
        res.send(result);
      }
    }
  );
});

The above replaceOne() method will match the document where the value of the name field is “Romeo” and will replace it with the new document. Let’s execute this route using the postman tool and see what happens.

Image from Gyazo

The replaceOne() method returns an object that contains three fields. The value of n is 1, this means, 1 document was matched. The value of nModified is also 1, this means, one document was replaced. Let’s verify through the mongo shell.

> db.kennel.find()
{ "_id" : ObjectId("5df390ce4e8d7e9979b2d21d"), "name" : "Rambo", "age" : 5, "breed" : "Pitbull" }
{ "_id" : ObjectId("5df390f34e8d7e9979b2d21e"), "name" : "Scooby Doo", "age" : 2, "breed" : "Great Dane" }
{ "_id" : ObjectId("5df391034e8d7e9979b2d21f"), "name" : "Johnny Boy", "age" : 2, "breed" : "Labrador", "__v" : 0 }
{ "_id" : ObjectId("5df391404e8d7e9979b2d220"), "name" : "Spike", "age" : 3, "breed" : "Pitbull" }
{ "_id" : ObjectId("5df391544e8d7e9979b2d221"), "name" : "Lui", "age" : 2, "breed" : "Pugg" }
>

The document where the value of the name field was ‘Romeo’ is replaced with the new document we specified inside the replaceOne() method.

The replaceOne() method only replaces the first matched document. If multiple documents can match the query, the replaceOne() method will ignore all the other documents. It will match only the first document.

Conclusion

We hope you enjoyed this article about the replaceOne function in mongoose. It is a great function to use in cases where you know the update you desire should only apply to one document because the replaceOne function will limit the interaction to just one document. When you’re dealing with database data you want to be careful that the queries you run don’t have unintended effects and this function is one great protection against that. For example if you are replacing a document based on a unique field, and you know it should only be replacing one document, this is a great function to use to ensure that it only effects one document.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.