【问题标题】:Fetch data using mongoose and Express/Node Js使用 mongoose 和 Express/Node Js 获取数据
【发布时间】:2020-07-01 10:13:40
【问题描述】:

我正在尝试使用 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;

这是控制台日志:


Server Started at PORT 4000
Connected to DB !!
Fetched

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

邮递员响应:'[]'

文档样本:

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

提示:当我使用另一个模型(“用户”)时,它可以正常工作并返回响应。

【问题讨论】:

  • 尝试添加 res.send({rdv}) 或 res.send(JSON.stringify(rdv))
  • 你能显示你的连接位吗?
  • @Zlatko 你的意思是数据库连接代码?
  • 是的,你在哪里启动服务器和连接?
  • 在另一个文件中,我已经获取的数据库连接没有问题,一切正常,我只是这个方法有问题。

标签: node.js mongodb express mongoose


【解决方案1】:

通过在模型中添加集合名称解决

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);

【讨论】:

    【解决方案2】:

    您的请求 .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}) )});
    });
    

    【讨论】:

    • 还是没有结果,{"rendezvous":[]}
    • 你确定你有数据库中的数据
    • 是的,我确实插入了同一个集合,它工作正常
    • 我认为您没有从数据库中获取数据,请尝试在 console.log(result) 上打印,您认为您从数据库中获取的结果,在我的案例中 try{ result .. .... 控制台日志(结果); } 只是为了测试你是否从数据库中获取数据,我认为你没有得到任何数据
    猜你喜欢
    • 2016-06-25
    • 2013-12-16
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多