Mongoose findOne() Function Explained with Examples

Updated: December 30, 2023 By: Guest Contributor Post a comment

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.