vincedd
vincedd

Reputation: 141

how to catch an error when using mongoose to query something

I am studying mongoose, and I have a example of a query:

async findOne(condition, constraints) {
        try {
            let data = await User.findOne(condition, constraints ? constraints : null);
            console.log(`findOne success--> ${data}`);
            return data;
        } catch (error) {
            console.log(`findOne error--> ${error}`);
            return error;
        }
    }

In my opinion,this code will catch errors when the method findOne won't work. Then I saw in the console there is a 'findOne success--> null' when the method findOne returns null. How can I make the try/catch work?

Upvotes: 9

Views: 15618

Answers (2)

Fraction
Fraction

Reputation: 12993

Mongoose's findOne() return null when there is no document found and null is not an error.

You can use .orFail() which throw an error if no documents match the given filter. This is handy for integrating with async/await, because orFail() saves you an extra if statement to check if no document was found:

let data = await User.findOne(condition, constraints ? constraints : null).orFail();

Or just throw an error when there is no result

try {
    let data = await User.findOne(condition, constraints ? constraints : null);
    if(!data) {
      throw new Error('no document found');
    }
    console.log(`findOne success--> ${data}`);
    return data;
} catch (error) {
    console.log(`findOne error--> ${error}`);
    return error;
}

Upvotes: 14

Beginner
Beginner

Reputation: 9135

you can add more conditions in the if of try block and throw a customError which will be catching at the catch block.

i hope this will solve the issue.

please see the below snippet

async findOne(condition, constraints) {
  try {
      let data = await User.findOne(condition, constraints ? constraints : null);
      console.log(`findOne success--> ${data}`);
      if(data){
        // do your logic
        return data;
      }
      const customError = {
        code : 500,
        message: 'something went wrong'
      }
      throw customError
  } catch (error) {
      console.log(`findOne error--> ${error}`);
      return error;
  }
}

Upvotes: 0

Related Questions