Any alternative for '<Modelname>.find()' function in mongoose

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

I am getting this error message when trying to run a callback function in the .find() mongoose method. Please suggest any alternative way to perform the operation done by the .find() method.

Hi @Ankit_Patnaik,

Welcome to the MongoDB Community forums :sparkles:

The usage of callback functions has been deprecated in Mongoose 7.x. Therefore, if you were using these functions with callbacks, it is recommended to use either async/await or promises. If async functions do not meet your requirements, you can go for promises.

// Before
conn.startSession(function(err, session) {
  // ...
});

// After
const session = await conn.startSession();
// Or:
conn.startSession().then(sesson => { /* ... */ });

I hope it helps!

Best,
Kushagra

1 Like

can you please tell me in which file i change?

if you were finding for example

List.find().then(function(lists){

//Return results

})

in the above, the List model is finding everything within the collection and you can tap on the results (lists) and then use the info the way you want. This solves that issue

2 Likes

My issue occurred in my controllers director in my API routes.

const router = require('express').Router();
const { Entry } = require("../../models");

router.get('/journal', async (req, res) => {
  //did not work (entry is my model)
  // Entry.find({}, (err, result) => {
  //   if (err) {
  //     res.send(err)
  //   }
  //   res.send(result)
  // })

//this worked
  Entry.find().then((err, result) => {
    console.log("result")
    if (err) {
      res.send(err)
    }
    res.send(result)
  })
});

module.exports = router;
1 Like