Sling Academy
Home/Node.js/Mongoose findOne() Function Explained with Examples

Mongoose findOne() Function Explained with Examples

Last updated: December 30, 2023

Introduction

Mongoose is a popular Node.js ODM library for interfacing with MongoDB. One of its fundamental database query functions is findOne(), which retrieves a single document from the database matching the given criteria.

The purpose of findOne() is to find the first document that matches the specified query criteria. If no document is found, it returns null.

Syntax and Parameters

The syntax of the findOne() function is as follows:

Model.findOne(query, [projection], [options], [callback])
  • query: An object specifying the search criteria.
  • projection: (Optional) An object or string specifying the fields to return.
  • options: (Optional) Additional options such as sort, skip, and others.
  • callback: (Optional) A function to execute if not using promises.

The function returns a query instance, which can be executed with a promise or by passing a callback.

Practical Examples

Example 1: Basic Usage

This example demonstrates how to use findOne() to retrieve a single document from a collection called ‘users’.

import mongoose from 'mongoose';

const userSchema = new mongoose.Schema({
  name: String,
  age: Number,
  email: String
});

const User = mongoose.model('User', userSchema);

async function findUserByName(userName) {
  try {
    const user = await User.findOne({ name: userName });
    console.log(user);
  } catch (error) {
    console.error(error);
  }
}

// Usage
findUserByName('Jane Doe');

Example 2: With Projection Parameter

This example shows how to use the projection parameter to return only specific fields of the document.

import mongoose from 'mongoose';

// existing User model and schema

async function findUserByEmail(userEmail) {
  try {
    const user = await User.findOne({ email: userEmail }, 'name age');
    // Only 'name' and 'age' fields will be returned
    console.log(user);
  } catch (error) {
    console.error(error);
  }
}

// Usage
findUserByEmail('[email protected]');

Conclusion

The findOne() function in Mongoose is a powerful tool for querying documents in a MongoDB collection. It offers a simple syntax with the flexibility to include projection and options parameters. Understanding how to use findOne() is fundamental in harnessing the capabilities of Mongoose for building Node.js applications backed by MongoDB.

Next Article: Mongoose: Sorting Documents by Multiple Fields

Previous Article: Understanding the Map schema type 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