skip to Main Content

I am getting this error will constructing a MERN page and couldn’t get the get format. Here is the code:

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const UserModel = require("./models/Users");

const cors = require("cors");

app.use(express.json());
app.use(cors());

mongoose.connect(
  "mongodb+srv://User:<password>@cluster0.o6pjbpq.mongodb.net/Database?retryWrites=true&w=majority" //Leave this part i have checked the mongoose.connect and no change.
);

app.get("/getUsers", (req, res) => {
  UserModel.find({}, (err, result) => {
    if (err) {
      res.json(err);
    } else {
      res.json(result);
    }
  });
});

app.post("/createUser", async (req, res) => {
  const user = req.body;
  const newUser = new UserModel(user);
  await newUser.save();

  res.json(user);
});

app.listen(3000, () => {
  console.log("SERVER RUNS PERFECTLY!");
});

I was expecting to get 200 OK and I am getting 500 Internal Server Error. And in the response page I am getting:

MongooseError: Model.find() no longer accepts a callback
    at Function.find (C:UsersFikirte AmareDesktopwebsiteservernode_modulesmongooselibmodel.js:2110:11)
    at C:UsersFikirte AmareDesktopwebsiteserverindex.js:16:13
    at Layer.handle [as handle_request] (C:UsersFikirte AmareDesktopwebsiteservernode_modulesexpresslibrouterlayer.js:95:5)
    at next (C:UsersFikirte AmareDesktopwebsiteservernode_modulesexpresslibrouterroute.js:144:13)
    at Route.dispatch (C:UsersFikirte AmareDesktopwebsiteservernode_modulesexpresslibrouterroute.js:114:3)
    at Layer.handle [as handle_request] (C:UsersFikirte AmareDesktopwebsiteservernode_modulesexpresslibrouterlayer.js:95:5)
    at C:UsersFikirte AmareDesktopwebsiteservernode_modulesexpresslibrouterindex.js:284:15
    at Function.process_params (C:UsersFikirte AmareDesktopwebsiteservernode_modulesexpresslibrouterindex.js:346:12)
    at next (C:UsersFikirte AmareDesktopwebsiteservernode_modulesexpresslibrouterindex.js:280:10)
    at cors (C:UsersFikirte AmareDesktopwebsiteservernode_modulescorslibindex.js:188:7)```

2

Answers


  1. Mongoose no longer supports callbacks, you can read more here

    You can try the following code on your get request:

    app.get("/getUsers", async (req, res) => {
      try {
        const result = await UserModel.find({});
        res.json(result);
      } catch (err) {
        res.json(err);
      }
    });
    
    Login or Signup to reply.
  2. Based on your error log and the comments/answers others have provided, you appear to be using Mongoose v7 or later, which explains the presence of this error in your console.

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

    One of the backwards-breaking changes introduced in Mongoose v7 dropped callback support. Simply put, many Mongoose functions now return promises instead of accepting callbacks.

    enter image description here

    Viewing the complete list, you will see that Model.find is among those listed.

    Unfortunately, many of the code snippets, tutorials, and even templates/repositories currently available have yet to reflect this change, which can lead to confusion, especially for newbies who aren’t yet familiar with the ins and outs of Mongoose.

    There are two ways to fix the error you are receiving.

    1. Refactor your callbacks to use async/await syntax.
    2. If that won’t work, instead, use promises, ergo, promise.then().catch().finally().

    If you need help refactoring a legacy codebase, the Mongoose documentation suggests using this conversion tool. NOTE: Your mileage may vary.

    Example using async/await

    // Before
    app.get('/getUsers', (req, res) => {
        UserModel.find({}, (err, result) => {
            if (err) {
                res.json(err)
            } else {
                res.json(result)
            }
        })
    })
    
    // After
    app.get('/getUsers', async (req, res) => {
        try {
            const result = await UserModel.find({})
            res.json(result)
        } catch (err) {
            res.json(err)
        }
    })
    
    

    Example using promise.then().catch().finally()

    // Before
    app.get('/getUsers', (req, res) => {
        UserModel.find({}, (err, result) => {
            if (err) {
                res.json(err)
            } else {
                res.json(result)
            }
        })
    })
    
    
    // After
    app.get('/getUsers', (req, res) => {
        UserModel.find({})
            .then((result) => {
                res.json(result)
            })
            .catch((err) => {
                res.json(err)
            })
    })
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search