Search code examples
node.jsmongodbmongoose

Mongoose - MongooseError: Model.find() no longer accepts a callback


Fruit.find().then((fruits) => {
    console.log(fruits);
});

The piece of code above works perfectly fine, but I would like to add and if-else condition to it, which in older versions of mongoose looks something like

Fruit.find(function(err, fruits) {
    if(err) {
        console.log('error occurred!');
    } else {
        console.log(fruits);
    }
});

Here's the error:

throw new MongooseError('Model.find() no longer accepts a callback');
    ^

MongooseError: Model.find() no longer accepts a callback

I have the latest version of mongoDB, i.e. 7.0.

I want the result to throw a message stating 'error occurred!' if there's an error in fetching the data, and log the data otherwise. Could someone please help me out? Thanks in advance!


Solution

  • Fruit.find()
      .then((fruits) => {
    }).catch((err) => console.log(err))
    

    You can catch the error with like that. Mongoose no longer accept callbacks. Or you may look for try-catch blocks

    try {
      const fruits = await Fruit.find({});
      console.log(fruits)
    } catch (error) {
      console.log(error)
    }