Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose stopped accepting callbacks for some of its functions

I've been using callbacks for .save() and .findOne() for a few days now and just today I encounter these errors:

throw new MongooseError('Model.prototype.save() no longer accepts a callback')

MongooseError: Model.prototype.save() no longer accepts a callback

and

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

It's really awkward given that callbacks are still accepted in the docs at least for .findOne().

app.post("/register", (req, res) => {
    const newUser = new User({
        email: req.body.username,
        password: req.body.password
    });

    newUser.save((err) => {
        if (err) console.log(err)
        else res.render("secrets");
    });
});

This is what used to work for me, using express and mongoose. Please let me know how to fix it.

like image 329
pablofdezr Avatar asked Sep 13 '25 15:09

pablofdezr


1 Answers

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

Since the callback function has been deprecated from now onwards. If you are using these functions with callbacks, use async/await or promises if async functions don't work for you.

app.get("/articles", async (req, res) => {
  try {
    const articles = await Article.find({ });
    res.send(articles);
    console.log(articles);
  } catch (err) {
    console.log(err);
  }
});
like image 175
Sunny Avatar answered Sep 15 '25 05:09

Sunny