How to use the mongoose findOneAndReplace function

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

Mongoose provides a few methods for replacing documents in a collection. One of these methods is findOneAndReplace(). This method finds a document according to the query and then replaces it with another document. It is quite similar to the replaceOne() method. But there is a difference in options. In both of these methods, we can provide optional parameters. Here lies the difference between the two methods. In this article, we will discuss more about the findOneAndReplace() method in mongoose.

We will use the details collection.

1
2
3
4
5
{ "_id" : ObjectId("5df91907306fc2afde3b6d90"), "name" : "John", "age" : 21, "location" : "New York" }
{ "_id" : ObjectId("5df9190b306fc2afde3b6d91"), "name" : "Sam", "age" : 25, "location" : "Chicago" }
{ "_id" : ObjectId("5df91911306fc2afde3b6d92"), "name" : "Lisa", "age" : 27, "location" : "Texas" }
{ "_id" : ObjectId("5df91915306fc2afde3b6d93"), "name" : "Max", "age" : 23, "location" : "New York" }
{ "_id" : ObjectId("5df9191b306fc2afde3b6d94"), "name" : "Ronn", "age" : 29, "location" : "Texas" }

We will use the postman tool for testing. You can download the postman tool from www.getpostman.com.

findOneAndReplace()

We will replace a document where the value of the location field is “New York”. The following route handler will be invoked when the endpoint ‘/replace’ is executed.

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

The findOneAndReplace() method has three mandatory parameters – a query, a new document, and a callback function. The callback function, in turn, has two parameters – an error(if any occurs) and the result. So let’s add this method to the router handler.

1
2
3
4
5
6
7
8
9
10
11
12
13
router.route("/replace").put(function(req, res) {
  details.findOneAndReplace(
    { location: "New York" },
    { name: "Sunny", age: 292, location: "Detroit" },
    function(err, result) {
      if (err) {
        res.send(err);
      } else {
        res.send(result);
      }
    }
  );
});

In the callback we specify what to do with both the error and the result. In this demo we actually will treat them the same. If we get an error we will return it back through the api with res.send(err) and in the case that the findOneAndReplace function is successful we will return it’s return value through the api with res.send(result).

Image from Gyazo

It returns the matched document. Let’s check through the mongo shell. We can do that with the command db.details.find() which will return all the documents in our details collection.

Image from Gyazo

Yes! It replaces the matched document. If we provide an empty object as a query, it matches the very first document.

As mentioned earlier, there is difference in options part in findOneAndReplace() and replaceOne() method. The findOneAndReplace() method has the following options:

  1. projection – This parameter allows you to pick which fields of the document you want to return from the function. If the document has a lot of fields but you only want to view the name or _id you may want to use this parameter.
  2. sort – If several documents match your query this parameter lets you set the order of those documents when choosing which one to update. For example if you wanted to only update the most recently updated document you might sort them in descending order by an updated timestamp.
  3. maxTimeMS – This parameter allows you to set a limit on how long this query takes to execute.
  4. rawResult – This parameter lets you control whether or not to return the raw result from the MongoDB driver.

Sort, maxTimeMS, returnNewDocument, and projection are missing in the replaceOne() method. But replaceOne() has options such as writeConcern and hint.

Conclusion

We hope this article about the mongoose findOneAndReplace() function has been helpful to you and that you can apply what you’ve learned to your specific scenario.

If you have any database needs please don’t hesitate to reach out to us at ObjectRocket. We are happy to discuss your specific problems and needs.

Thanks for checking out another one of our knowledge-base articles! There are many more on mongoose and MongoDB as well as PostgreSQL, Redis, Elasticsearch and much much more.

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.