Mongoose Query.prototype.orFail() API
The Mongoose Query API.prototype.orFail() method of the Mongoose API is used on Query objects. It allows us to throw custom errors if no documents match the given filter condition. This method accepts a parameter to provide custom error message. If we do not provide any parameter and no document matches the filter condition than orFail() method will throw DocumentNotFoundError error. Let us understand orFail() method using an example.
Syntax:
query.find(...).orFail( error_message );
Parameters: This method accepts a single parameter as described below:
- error: It is used to specify the new custom error object.
Return Value: This method returns the Query object, on which we can call callback function.
Setting up Node.js Mongoose Module:
Step 1: Create a Node.js application using the following command:
npm init
Step 2: After creating the NodeJS application, Install the required module using the following command:
npm install mongoose
Project Structure: The project structure will look like this:
Database Structure: The database structure will look like this, the following database present in the MongoDB.
Example 1: The below example illustrates the basic functionality of the Mongoose Connection orFail() method. In this example, we are fetching the document with value “Student4” for the field name but collection does not found the document. Hence, at the end we are getting DocumentNotFoundError error.
Filename: app.js
Javascript
// Require mongoose module const mongoose = require( "mongoose" ); // Set Up the Database connection const connectionObject = mongoose.createConnection(URI, { useNewUrlParser: true , useUnifiedTopology: true , }); const studentSchema = new mongoose.Schema({ name: { type: String, required: true }, age: Number, rollNumber: { type: Number, required: true } }); const StudentModel = connectionObject.model( 'Student' , studentSchema ); const query = StudentModel.find(); query.find({ name: "Student4" }).orFail() query.exec((error, result) => { if (error) { console.log( "Error -" , error); } else { console.log( "Result -" , result); } }) |
Step to run the program: To run the application execute the below command from the root directory of the project:
node app.js
Output:
Error – DocumentNotFoundError: No document found for query “{ name: ‘Student4’ }” on model “Student”
at _orFailError (D:\GeeksforGeeks\Articles\Sakshi\Mongoose Query API.prototype.orFail()\node_modules\mongoose\lib\query.js:4870:11)
at D:\GeeksforGeeks\Articles\Sakshi\Mongoose Query API.prototype.orFail()\node_modules\mongoose\lib\query.js:4813:17
at D:\GeeksforGeeks\Articles\Sakshi\Mongoose Query API.prototype.orFail()\node_modules\mongoose\lib\query.js:4973:15
at cb (D:\GeeksforGeeks\Articles\Sakshi\Mongoose Query API.prototype.orFail()\node_modules\mongoose\lib\query.js:2258:14)
at D:\GeeksforGeeks\Articles\Sakshi\Mongoose Query API.prototype.orFail()\node_modules\mongodb\lib\utils.js:349:28
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
result: undefined,
numAffected: undefined,
filter: { name: ‘Student4’ },
query: { name: ‘Student4’ }
}
Example 2: The below example illustrates the basic functionality of the Mongoose Connection orFail() method. In this example, we are fetching the document with value “101” for the field rollNumber but collection does not found the document. Hence, at the end we are sending custom error message.
Filename: app.js
Javascript
// Require mongoose module const mongoose = require( "mongoose" ); // Set Up the Database connection const connectionObject = mongoose.createConnection(URI, { useNewUrlParser: true , useUnifiedTopology: true , }); const studentSchema = new mongoose.Schema({ name: { type: String, required: true }, age: Number, rollNumber: { type: Number, required: true } }); const StudentModel = connectionObject.model( 'Student' , studentSchema); const query = StudentModel.find(); query.find({ rollNumber: 101 }).orFail( new Error( "Roll number entered incorrected." ) ) query.then((res => { console.log(res); })). catch ((err) => { console.log(err); }) |
Step to run the program: To run the application execute the below command from the root directory of the project:
node app.js
Output:
Error: Roll number entered incorrected.
at Object.<anonymous> (D:\GeeksforGeeks\Articles\Sakshi\Mongoose Query API.prototype.orFail()\app.js:22:38)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
Reference: https://mongoosejs.com/docs/api/query.html#query_Query-orFail
Please Login to comment...