Sling Academy
Home/Node.js/Using the Mongoose Model.find() function (with examples)

Using the Mongoose Model.find() function (with examples)

Last updated: December 30, 2023

Mongoose’s Model.find() function is quintessential for querying documents from a MongoDB database using the Mongoose ORM in a Node.js environment. It allows you to retrieve a set of documents that match given criteria. This function was available in Mongoose since its early versions, adapting and evolving over the years with JavaScript and Node.js standards, including the incorporation of Promises and async/await.

The purpose of the Model.find() method is to search for documents within a MongoDB collection and return them as an array of document instances. It supports query conditions, projection, and options like sorting, limiting the number of documents, etc.

Syntax and Parameters

Model.find(query, [projection], [options], [callback])
  • query: specifies the conditions that documents must meet to be selected.
  • projection: optionally specifies the fields to return.
  • options: additional options such as sort, limit, skip, etc.
  • callback: optional callback for handling the results. If not provided, find() will return a Promise.

When the callback is not provided, find() returns a Promise which, when resolved, yields an array of documents matching the criteria.

Code Examples

Basic Find Example

The code below shows you how to get documents without any conditions:

import mongoose from 'mongoose';
const { Schema, model } = mongoose;

mongoose.connect('mongodb://localhost:27017/mydatabase');

const userSchema = new Schema({ name: String, age: Number });
const User = model('User', userSchema);

async function findUsers() {
  const users = await User.find();
  console.log(users);
}

findUsers();

Query Conditions Example

This example retrieves documents that match specific conditions:

... // assume previous User model declaration

async function findSpecificUsers() {
  const youngUsers = await User.find({ age: { $lt: 30 } });
  console.log(youngUsers);
}

findSpecificUsers();

Projection Example

In this example, we’ll retrieve only specified fields from matching documents:

... // assume previous User model declaration

async function findUserNames() {
  const names = await User.find({}, 'name');
  console.log(names);
}

findUserNames();

Complex Query with Options

This example demonstrates sorting and limiting results:

... // assume previous User model declaration

async function findSortedLimitedUsers() {
  const sortedUsers = await User.find({}, null, { limit: 5, sort: 'age' });
  console.log(sortedUsers);
}

findSortedLimitedUsers();

Conclusion

The Model.find() function is a robust and vital part of Mongoose’s querying capabilities, offering flexibility and efficiency when handling MongoDB data. Through its evolving syntax and conformance to modern JavaScript practices, it remains an agile tool for Node.js developers.

Next Article: Understanding Mongoose deleteMany() function (with examples)

Previous Article: How to Specify a Custom Error Message in Mongoose

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates