Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

How does Query.prototype.error() work in Mongoose?

  • Last Updated : 17 Mar, 2021

The Query.prototype.error() function is used to sets/gets the error flag on this query. If this flag is undefined or not null then the exec() promise will reject without executing.

Syntax:

Query.prototype.error()

Parameters: This function has one err parameter of Error type.
Return Value: This function returns Query Object.
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

Now, create a folder and add a file, for example, index.js as shown below.



Database: The sample database used here is shown below: 
 

Project Structure: The project structure will look like this.

Example 1:

index.js




const mongoose = require('mongoose');
  
// Database connection
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});
  
// User model
const User = mongoose.model('User', { 
    name: { type: String },
    age: { type: Number }
});
  
var query = User.find().error(new Error("MY ERROR MESSAGE"))
query.exec(function(err, res){
    if(err) console.log(err.message)
    else console.log(res)
});

Run index.js file using below command: 

node index.js

Output:

MY ERROR MESSAGE

Example 2:

index.js




const express = require('express');
const mongoose = require('mongoose');
const app = express()
  
// Database connection
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true
});
  
// User model
const User = mongoose.model('User', { 
    name: { type: String },
    age: { type: Number }
});
  
var query = User.find().error(new Error("MY CUSTOM ERROR MESSAGE"))
query.exec(function(err, res){
    if(err) console.log(err.message)
    else console.log(res)
});
  
app.listen(3000, function(error ) {
    if(error) console.log(error)
    console.log("Server listening on PORT 3000")
});

Steps to run the program: 
 

Run index.js file using below command: 
 

node index.js

Output: 

Server listening on PORT 3000
MY CUSTOM ERROR MESSAGE

Reference: 
https://mongoosejs.com/docs/api/query.html#query_Query-error
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :