How does Query.prototype.catch() work in Mongoose ?
The Query.prototype.catch() function executes the query and returns a promise which can be resolved with either the doc(s) or rejected with the error.
Syntax:
Query.prototype.catch()
Parameters: This function has one parameter i.e. a reject callback function.
Return Value: This function returns a promise.
Installing mongoose :
npm install mongoose
After installing the mongoose module, you can check your mongoose version in command prompt using the command.
npm mongoose --version
After that, you can just create a folder and add a file for example, index.js as shown below.
Database: The sample database used here is shown below:
Example 1:
index.js
const mongoose = require( 'mongoose' ); // Database connection mongoose.connect( 'mongodb://127.0.0.1:27017/w3wiki' , { useNewUrlParser: true , useCreateIndex: true , useUnifiedTopology: true }); // User model const User = mongoose.model( 'User' , { name: { type: String }, age: { type: Number } }); const promise = User.find({age: "Not a number" }); promise. catch ( function (error) { console.log( "Error Occurred:" , error.message) }) |
The project structure will look like this:
Run index.js file using below command:
node index.js
Output:
Error Occurred: Cast to Number failed for value "Not a number" at path "age" for model "User"
Example 2:
index.js
const express = require( 'express' ); const mongoose = require( 'mongoose' ); const app = express(); // Database connection mongoose.connect( 'mongodb://127.0.0.1:27017/w3wiki' , { useNewUrlParser: true , useCreateIndex: true , useUnifiedTopology: true }); // User model const User = mongoose.model( 'User' , { name: { type: String }, age: { type: Number } }); const promise = User.find({ age: "Not a number" }); promise. catch ( function (error) { console.log( "Error Occurred:" , error.message) }) app.listen(3000, function (error ) { if (error) console.log(error) console.log( "Server listening on PORT 3000" ) }) |
The project structure will look like this:
Run index.js file using below command:
node index.js
Output:
Server listening on PORT 3000 Error Occurred: Cast to Number failed for value "Not a number" at path "age" for model "User"
Reference:https://mongoosejs.com/docs/api/query.html#query_Query-catch