简体   繁体   English

使用 mongoose 和 Express/Node Js 获取数据

[英]Fetch data using mongoose and Express/Node Js

i am trying to fetch data from a MongoDB database using mongoose and express in Node js , i created the Model and successfully connected to database but the problem is i am getting an empty response while there already documents in the database collection .我正在尝试使用 mongoose 从 MongoDB 数据库中获取数据,并在 Node js 中表达,我创建了模型并成功连接到数据库,但问题是我得到一个空响应,而数据库集合中已经有文档。

Model class :模型类:

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 :索引.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;

this is the console.log :这是 console.log :


Server Started at PORT 4000
Connected to DB !!
Fetched

Postman GET request on : ' http://localhost:4000/user/GetRdvMedecin '邮递员 GET 请求:' http://localhost:4000/user/GetRdvMedecin '

Postman Response : ' [] '邮递员回复:'[]'

document sample :文件样本:

{
  "_id":{
    "$oid":"5e7396787b32a12e38a7aa7d"
  },
  "idpatient":"5e6ce11bc31de6132ca454a1",
  "idmedecin":"5e5aa519190d8c2818a66a0a"
}

Hint : when i used another model ('user') it works fine and returns a response .提示:当我使用另一个模型(“用户”)时,它工作正常并返回响应。

Your request .find() could return more than one object, I always return something like this:您的请求 .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}) )});
});

Solved by adding the name of collection in the model通过在模型中添加集合名称解决

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM