How to find documents in Mongoose

Mongoose models provide several static methods to retrieve one and more documents from a MongoDB collection.

Let us say you have the following Mongoose model Product that contains information about the products you are selling on your website:

const mongoose = require('mongoose')
const { Schema } = mongoose

const Product = mongoose.model(
  'Product',
  new Schema({
    name: String,
    color: String,
    price: Number
  })
)

Find a single document

To retrieve a single document from a MongoDB collection, you can use the findOne() method:

const doc = await Product.findOne({ name: 'MacBook Pro' })

The findOne() method takes in a JSON object as a query filter. If the filter object is null or undefined, Mongoose will send an empty command to retrieve an arbitrary document.

Mongoose provides another method called findById() to retrieve one document by its _id. This method takes in the document ID and returns a promise that resolves to a Mongoose document or null if no document was found.

await Product.create({ _id: 'X2B' })

// { _id: 'X2B' }
const doc = await Product.findById('X2B')

The findById() method is just a wrapper on top of findOne(). When you call findById(), Mongoose calls findOne() under the hood to retrieve the requested document.

Find multiple documents

To retrieve a list of all products in the collection, you can use the find() method with an empty object as the first parameter:

const docs = await Product.find({})

The find() method is a powerful tool for querying a MongoDB database. It accepts a filter object and returns all documents that match the filter. The filter object can contain equality checks, comparisons, regular expressions, and compositions.

The following example demonstrates how you can retrieves all black color products with a price range of 5 and 15:

const docs = await Product.find({
  color: 'Black',
  price: {
    $gte: 5,
    $lte: 15
  }
})

What if you have millions of products in the collection? Loading all your products into memory at once is not a good idea.

To iterate over all products one at a time without loading them all into memory at once, you should use the cursor() helper method:

const cursor = Product.find().cursor()

for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) {
  console.log(doc)
}

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.