Reputation: 29
I'm new to MERN and stackoverflow. I want to get all data from mongodb database. But when I try it through postman, It shows following error.
Here is my Model.js file Model.js
const mongoose = require("mongoose");
const Schema = {
name: {
type: String,
required: true
},
code: {
type: String,
required: true
},
passMark: {
type: Number,
required: true
},
lic: {
type: String,
required: true
},
subjects: [
{
type: mongoose.Schema.Types.ObjectId,
required: false,
ref: 'Subjects'
}
]
};
const Model= mongoose.model("Model",Schema);
module.exports = Model;
Here is my router.js file Router.js
const Model= require("../models/Model");
const route = require("express").Router();
route.get("/", (req,res)=>{
Model.find()
.exec((err, items)=>{
if(!err){
return res.json({items: items})
}
})
});
Someone can help me to fix this issue.
Upvotes: 1
Views: 2789
Reputation: 26370
That's a blind guess, but I believe the error occurs because Model.find()
does not return JSON data. It returns a collection of Mongoose objects, with extra methods like .save()
. If you want pure JSON out of Mongo, add .lean()
:
route.get("/", (req,res)=>{
Model.find().lean()
.exec((err, items)=>{
if(!err){
return res.json({items: items})
}
})
});
Pro tip, same thing using the async/await syntax :
route.get("/", async (req,res)=>{
try{
const items = await Model.find().lean().exec(); // .exec() returns a true Promise
res.json({items});
} catch(err) {
res.status(500).end(err)
}
});
Upvotes: 1