[英]Fetch data using mongoose and Express/Node Js
我正在尝试使用 mongoose 从 MongoDB 数据库中获取数据,并在 Node js 中表达,我创建了模型并成功连接到数据库,但问题是我得到一个空响应,而数据库集合中已经有文档。
模型类:
const mongoose = require("mongoose");
const RendezvousSchema = mongoose.Schema({
idpatient: {
type: String,
required: true
},
idmedecin: {
type: String,
required: true
},
});
module.exports = mongoose.model("Rendezvous", RendezvousSchema);
索引.js:
const express = require("express");
const router = express.Router();
const Rendezvous = require("../model/RendezVous");
/* Get Rendez Vous By id */
/**
* @method - GET
* @description - Get Rendez vous Medecin
* @param - /user/GetRdvMedecin
*/
router.get("/GetRdvMedecin", async (req, res) => {
try {
const rdv = await Rendezvous.find();
res.json(rdv);
console.log('Fetched');
} catch (e) {
res.send({ message: "Error in Fetching rendez vous" });
}
});
/* Get Rendez Vous By id*/
module.exports = router;
这是 console.log :
Server Started at PORT 4000
Connected to DB !!
Fetched
邮递员 GET 请求:' http://localhost:4000/user/GetRdvMedecin '
邮递员回复:'[]'
文件样本:
{
"_id":{
"$oid":"5e7396787b32a12e38a7aa7d"
},
"idpatient":"5e6ce11bc31de6132ca454a1",
"idmedecin":"5e5aa519190d8c2818a66a0a"
}
提示:当我使用另一个模型(“用户”)时,它工作正常并返回响应。
您的请求 .find() 可以返回多个对象,我总是返回如下内容:
router.get("/GetRdvMedecin", async (req, res) => {
let results;
try {
results = await Rendezvous.find();
} catch (e) {
res.send({ message: "Error in Fetching rendez vous" });
}
res.json({rendezvous: results.map(result => result.toObject({getters: true}) )});
});
通过在模型中添加集合名称解决
const mongoose = require("mongoose");
const RendezvousSchema = mongoose.Schema({
idpatient: {
type: String
},
idmedecin: {
type: String
}
},{
collection: 'Rendezvous'
});
// export model user with UserSchema
module.exports = mongoose.model("Rendezvous", RendezvousSchema);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.