How to Find Documents with Mongoose

Introduction

If you’re using the popular Schema/Model based library Mongoose to interact with MongoJS from NodeJS then this article will help you find documents. We will detail a few of the common options for finding documents. Whether you need to find all the documents, a single document by id, or limit to a set number of documents this tutorial should give set you on the right path to creating the right query with Mongoose.

Prerequisites

  • You should have NodeJS installed.
  • You should have Mongoose installed.
  • Some command line experience is recommended.

Demo Examples

For all of our examples we will be using a model called ProductModel so you should modify any queries with your Model name.

Find all documents

To find all documents you’ll use the .find() whose defintion is below:

Model.find():
conditions (Object)
[projection] (Object|String) optional fields to return, see Query.prototype.select()
[options] (Object) optional see Query.prototype.setOptions()
[callback] (Function)

Find all documents we use the find() function with the conditions object empty:

ProductModel.find({});

Find documents by a field condition

To look for Products with a brand name we would execute a query like this:

ProductModel.find({ brand: 'Nike'});

To find Products with a field in a numeric range you would do something like this:

ProductModel.find({ quantity: { $gte: 100 }});

Combining conditions

To combine the conditions above just include them in the same object like this:

ProductModel.find({ brand: 'Nike', quantity: { $gte: 100 }});

Callbacks

If you want to execute some functionality on the documents returned you can use the callback parameter like so:

ProductModel.find({ brand: 'Nike', quantity: { $gte: 100 }}, function (err, docs) {
  console.log(docs);
});

Instead of logging the docs you can loop through them and do whatever you’d like.

Find with a regex

To find with a regex you can include the regular expression directly in the value like this:

ProductModel.find({ brand: /nike/i });

Limit results to only certain fields

If you don’t want the results to have every field you can specify the fields you want in the second parameter (projections) like so:

// We only want the brand and quantity fields returned
ProductModel.find({ brand: 'Nike' }, 'brand quantity');

Use the options to use features such as skip

You can use the options parameter to do things such as skipping results for pagination:

ProductModel.find({ brand: 'Nike' }, 'brand quantity', { skip: 5 });

Find by Id

Now we’ll look at the findById() function and how to utilize it. Let’s look at it’s function definition first:

Model.findById()
Parameters
id (Object|String|Number) value of _id to query by
[projection] (Object|String) optional fields to return, see Query.prototype.select()
[options] (Object) optional see Query.prototype.setOptions()
[callback] (Function)

Let’s take a look at a few examples of how to use this.

First let’s just get a single Product by id:

ProductModel.findById(id, function (err, product) {
  console.log(product);
});

Use find by id and limit to the fields brand and quantity:

ProductModel.findById(id, 'brand quantity', function (err, product) {
  console.log(product);
});

Retrieve a Product by id with all the fields EXCEPT for brand:

ProductModel.findById(id, '-brand', function (err, product) {
  console.log(product);
});

Conclusion

We hope this short tutorial acquainted you with the Mongoose syntax and functionality for finding documents in Mongo. We hope you can apply what you saw here to your application. If you have any questions or feedback please don’t hesitate to reach out to us.

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.