I’m working with a simple GET request but it returns nothing in the browser with no warnings. I checked all the connections to Mongoose works perfectly and collection name are correct.
const uriAtlas = "mongodb://localhost:27017/appfullMern";
mongoose.connect(uriAtlas).then(() =>
console.log("successful connexion DB")
);
const Schema = mongoose.Schema;
let departSchema = new Schema(
{
code: Number,
name: String,
},
{ versionKey: false }
);
let Depart = mongoose.model("depart", departSchema);
app.get("/", (req, res) => {
Depart.find({}, (err, results) => {
if (!err) {
res.send(results);
}
});
});
3
Answers
well solved question it turns that
let Depart = mongoose.model("depart", departSchema);
will automatically create a table in plural form which means is this case it will create departs so to avoid this problem we need to add more parameters to it so it will belet Depart = mongoose.model("depart", departSchema,"depart");
Please try and wrap the code in a try-catch, but also you’re only returning a response if no error. This is bad error handling, as errors or response will bug silently.
First of all, make sure the request you are making to your app returns with a 200 status. This way you can discard that the problem is with the request per se and not with the response being empty.
Also, consider using async/await syntax instead. Please refactor your code like so and check again: