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.

This widget is not supported in dev-mode. Kindly enable it or run using yarn webapp:dev-widgets.

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