skip to Main Content

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.

8

Answers


  1. app.post("/login",function(req,res){
        const username = req.body.username;
        const password = req.body.password;
    
        User.findOne({email:username})
        .then((foundUser) => {
            if(foundUser){
                if(foundUser.password === password){
                    res.render("secrets");
                }
            }
       })
       .catch((error) => {
           //When there are errors We handle them here
    
    console.log(err);
           res.send(400, "Bad Request");
       });
          
    });
    

    This works for me, also im doing the web dev bootcamp by angela yu.

    It seems like now you have to use => then and =>catch for the handling

    Login or Signup to reply.
  2. app.post("/register", function(req, res){
        const newUser = new User({
            email: req.body.email,
            password: req.body.password
        });
    
        newUser.save().then(()=>{
            res.render("secrets");
        }).catch((err)=>{
            console.log(err);
        })
    });
    

    Hope it helped!

    Login or Signup to reply.
  3. 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);
      }
    });
    
    Login or Signup to reply.
  4. Good day to everyone! Mongoose has just made a new update, mongoose has now got rid of callbacks. So that means, now instead of doing this

    //Old way ( doesn't work anymore )
    
    data.save((err, result) => {
       if(!err) console.log(result);
    })
    

    You should do it like this!

    //New way ( use this in your projects )
    
    let output;
    (async () => {
       output = await data.save();
    })
    console.log(output);
    

    This also applies for every other mongoose callback

    Login or Signup to reply.
  5. // old way (deprecated)
    
    Model.find(function(err, models){
      if (err) {
        console.log(err);
      }else {
        console.log(models);
      }
    });
    
    
    // new way
    
    Model.find()
    .then(function (models) {
      console.log(models);
    })
    .catch(function (err) {
      console.log(err);
    });
    
    Login or Signup to reply.
  6. In index.js
    
    const mongoose = require('mongoose');
    
    var mongoURI = 'mongodb+srv://<username>:<password>@cluster0.mgwgzxk.mongodb.net/test' 
    
    const connectToMongo =  () => {
         mongoose.connect(mongoURI)
         .then( ()=>
            console.log("Connected to mongo Successful")
        )
    }
    
    
    module.exports = connectToMongo;
    
    Login or Signup to reply.
  7. Anyone whose facing issue connecting to mongodb. Just use async await and you are good to go…

    const mongoose = require('mongoose');
    
    const mongoURI = "Connection URI";
    
    const connectToMongo = async () => {
     mongoose.connect(mongoURI, await console.log("Connected to mongo `Successful")`
        );
    }
    
    module.exports = connectToMongo;
    
    Login or Signup to reply.
  8. You can either use then catch or async await

    then catch method:

    mongoose
      .connect(process.env.MONGO_URI)
      .then(() => {
        console.log("Connected to MongoDB");
      })
      .catch((err) => {
        console.log(err);
      });
    

    async await method:

    const connectToMongo = async () => {
      await mongoose.connect(process.env.MONGO_URL);
      console.log("Connected to MongoDB");
    };
    
    connectToMongo();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search