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
Mongoose no longer supports callbacks, you can read more here
You can try the following code on your get request:
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.
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.
Viewing the complete list, you will see that
Model.find
is among those listed.There are two ways to fix the error you are receiving.
async/await
syntax.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
Example using
promise.then().catch().finally()