node.js - 使用 mongoose 和 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);
index.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}) )});
});
推荐阅读
- peoplecode - 如何解决“获取数组元素 2:索引不在 1 到 1 范围内”?
- html - 修复 Safari 加载 iframe 放大
- c - 输入错误后程序发疯(C)
- jquery - 使用数据属性作为选择器的最短方法是什么?
- php - 如何使用codeigniter显示mysql数据透视表数据
- json - 如何使用对象映射器快速解析我们解析数组的字典
- if-statement - 元组中带有搜索文本条件的 if 语句
- python - 当我打开这个抓取代码时,结果是空的
- android - 如何仅在连接到某些网络或 VPN 时运行 android 应用程序?
- jenkins - 使用 Jenkins 为本地 kubernetes 集群实施 CD?