[英]How to get data from model in node express?
I'm new to MERN and stackoverflow.我是 MERN 和 stackoverflow 的新手。 I want to get all data from mongodb database.我想从 mongodb 数据库中获取所有数据。 But when I try it through postman, It shows following error.但是当我通过 postman 尝试时,它显示以下错误。
Here is my Model.js file Model.js这是我的 Model.js 文件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这是我的 router.js 文件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.有人可以帮我解决这个问题。
That's a blind guess, but I believe the error occurs because Model.find()
does not return JSON data.这是一个盲目的猜测,但我相信错误的发生是因为Model.find()
没有返回 JSON 数据。 It returns a collection of Mongoose objects, with extra methods like .save()
.它返回 Mongoose 对象的集合,并带有额外的方法,例如.save()
。 If you want pure JSON out of Mongo, add .lean()
:如果你想要纯 JSON 从 Mongo 出来,添加.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:专业提示,使用 async/await 语法同样的事情:
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)
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.