The mongoose exists function

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

Introduction

There are typically large amounts of documents in a MongoDB collection. There are occasions when you want to check if a document exists, often before performing a second operation if it does. For that occasion mongoose provided the very handy exists() method. In this article, we will discuss the mongoose exists() method and how to use it.

Remember that mongoose is a very popular ODM library for MongoDB. It’s easy to install and get started but for this article we will focus on the exists() method.

Let’s jump in.

We will be using the exists() method on our kennel collection which contains the following data:

1
2
3
4
5
{ "_id" : ObjectId("5df390ce4e8d7e9979b2d21d"), "name" : "Rambo", "age" : 5, "breed" : "Pitbull" }
{ "_id" : ObjectId("5df390f34e8d7e9979b2d21e"), "name" : "Scooby Doo", "age" : 2, "breed" : "Great Dane" }
{ "_id" : ObjectId("5df391404e8d7e9979b2d220"), "name" : "Spike", "age" : 3, "breed" : "Pitbull" }
{ "_id" : ObjectId("5df391544e8d7e9979b2d221"), "name" : "Lui", "age" : 2, "breed" : "Pugg" }
{ "_id" : ObjectId("5df49352cfc314ad6829bf5f"), "name" : "Johnny Boy", "age" : 3, "breed" : "Labrador" }

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

exists()

The exists() method returns a boolean value, i.e. either true or false. This method checks if a particular document exists in a collection or not. The exists method takes a query as a parameter and if the query matches a document in the collection, it returns true. The exists() method can be useful when we need to make decisions in the backend. It is very useful with the if statement. Using this method is also very easy and simple. Let’s try it.

The following router handler will be invoked when the endpoint ‘/docexists’ will be executed.

1
router.route("/docexists").get(function(req, res) {});

Let’s add the exists() method.

1
2
3
4
5
6
7
8
9
router.route("/docexists").get(function(req, res) {
  kennel.exists({ name: "Rambo" }, function(err, result) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

The exists() method has two parameters – a query and a callback function. The callback function, in turn, has two parameters – an error (if any occurs) and the result.

Using the exists() method, we are looking for a document where the value of the name field is “Rambo”. Let’s check what the exists() method returns using the postman tool.

Image from Gyazo

It returns true! That means a document with the name field’s value “Rambo” exists in the kennel collection.

We can also provide multiple conditions in a query.

1
2
3
4
5
6
7
kennel.exists({ name: "Rambo", age: "10" }, function(err, result) {
  if (err) {
    res.send(err);
  } else {
    res.send(result);
  }
});

Here, we have two conditions.

1
{"name" : "Rambo", "age" : "10"}

The exists() method will only return true if both the conditions are matched with a document. Let’s check using the postman tool.

Image from Gyazo

It returns false! There is a document where the value of the name field is “Rambo”, but the value of the age field in that document is not equal to the value we specified in the condition.

Conclusion

In this article we have shown you how to use the exists function in mongoose. You can provide it with multiple conditions and it will check if there is a document in the collection that matches all those conditions. The exists function takes a callback that executes upon completion. That function has two inputs, an error ( if one occurs), and the result. The result is a boolean (true or false) indicating whether a document exists that matches those conditions. This function is handy in lots of situations so add it to your toolbelt.

We hope this tutorial was informative. Please don’t hesitate to reach out to us at Object Rocket if you have any database needs. Thanks for your time.

Code Recap

1
2
3
4
5
6
7
kennel.exists({ name: "Rambo", age: "10" }, function(err, result) {
  if (err) {
    res.send(err);
  } else {
    res.send(result);
  }
});

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.