9

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?

2 Answers 2

14

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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;
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.