【问题标题】:Postman Returning Empty when using GET request邮递员在使用 GET 请求时返回空
【发布时间】:2021-05-10 08:36:44
【问题描述】:

我正在使用 mongodb、js、express 和 postman 开发一个 RESTful API 来测试它。我正在尝试连接到我的云图集 mongodb 集群并检索所有信息。但是,在邮递员上测试时,它返回空:[]

我可以很好地连接到数据库,并且我的集合中有 3 个文档。数据库名为mobile_phone_store,集合名为personal_information

这是我的 server.js

const express = require("express");
const mongoose = require("mongoose");
const infoRoute = require("./app/routes/db.routes.js");

const app = express();

app.use(express.json());

mongoose.connect(
"mongodb+srv://*************************/mobile_phone_store?retryWrites=true&w=majority", {
    useNewUrlParser: true,
    useFindAndModify: false,
    useUnifiedTopology: true
  }
);

app.use(infoRoute);

app.listen(3000, () => {
console.log("Server is running...");
}); 

这是我的 db.model.js

  const mongoose = require('mongoose');
 // create a mongoose schema for a quotation
const PersonalInfoSchema = mongoose.Schema({
    customerID: String,
    Title: String,
    Fname: String,
    Lname: String,
    mobile: String,
    email: String
},     {

    timestamps: true
});
 // export the model to our app

 const personal_information = mongoose.model("personal_information", PersonalInfoSchema);

 module.exports = personal_information;

这是我的 db.routes

  const express = require("express");
  const Model = require("../models/db.model");
  const app = express();

 app.get("/personal_informations", async(request, response) => {
     const infos = await Model.find({});

     try {
         response.send(infos);
    } catch (error) {
         response.status(500).send(error);
    }
    });

 module.exports = app;

在邮递员中,我使用的是 URL http://localhost:3000/personal_informations。有任何想法吗?我一直在寻找解决方案一段时间,但我没有找到任何东西

【问题讨论】:

  • 您在响应中看到的状态是什么?在发送响应之前尝试记录infos
  • 当我尝试 console.log(infos);它还返回 []
  • 尝试将 const infos = await... 行放入 try 块中

标签: javascript mongodb api


【解决方案1】:

问题可能与 MongoDB 连接有关。

connect 解析时试听一下:

mongoose
  .connect(
    'mongodb+srv://*************************/mobile_phone_store?retryWrites=true&w=majority',
    {
      useNewUrlParser: true,
      useFindAndModify: false,
      useUnifiedTopology: true,
    }
  )
  .then(() => {
    app.listen(3000, () => {
      console.log('Server is running...');
    });
  })
  .catch((err) => console.log(err));

【讨论】:

  • 好的,取得了一些进展,但是现在邮递员返回一个错误,说它无法获取个人信息,即:
    Cannot GET /personal_informations
  • 顺便说一句,它连接到数据库就好了
  • @tinaburner 尝试将 app.get("/personal_informations"... 在连接 sn-p 之前放入 server.js 中
  • 它仍然返回 []
  • @tinaburner 确保集合中有文档并尝试发送测试响应,例如response.send('test');
猜你喜欢
  • 2019-01-07
  • 2020-07-23
  • 2021-10-24
  • 2020-05-15
  • 2021-10-16
  • 2019-08-25
  • 1970-01-01
  • 2022-01-12
  • 2019-10-12
相关资源
最近更新 更多