What is exists() in Mongoose?

exists is a Mongoose method or function that is used to check if at least one document exists that matches a specified filter. If there is a match, true is returned. Otherwise, false is returned.

Syntax

Model.exits(filter)

Parameter

filter: The specified filter. It is an object that contains a path or paths with a specified value to match the documents.

Return value

A Boolean value is returned, which is either true or false. true is returned when at least one document that matches the filter exists in the collection. Otherwise, false is returned.

Code

In the example below, we demonstrate the use of the exists() method. We create a product Schema and check if a certain product exists in the collection using the exists() method.

// import mongoose
const mongoose = require("mongoose");
// creating a product Schema with mongoose
let Product = mongoose.model("Item", new mongoose.Schema({
name: String,
category: Number,
price: Number,
tag: String
})
)
// check if product Educative.io
// exists with the exists() method
let product = await Product.exists({name: "Educative.io"});
console.log(product) // true

If product from the code above is logged to the console, a true value is returned because Educative.io is a product that exists in the collection.

Free Resources