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.