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.
Model.exits(filter)
filter
: The specified filter. It is an object that contains a path or paths with a specified value to match the documents.
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.
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 mongooseconst mongoose = require("mongoose");// creating a product Schema with mongooselet Product = mongoose.model("Item", new mongoose.Schema({name: String,category: Number,price: Number,tag: String}))// check if product Educative.io// exists with the exists() methodlet 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.