繁体   English   中英

NodeJS Express Mongoose 返回空 []

[英]NodeJS Express Mongoose return empty []

我试图制作一个 MEAN 堆栈应用程序,但我的 API 无法提供我请求的数据。

服务器.js 文件:

const express = require("express");
const bodyparser = require("body-parser");
const mongoose = require('mongoose');
const dotenv = require('dotenv');
dotenv.config();
const port = process.env.PORT; 
const dburi = process.env.DB_URI; 

//Routes
const volcanoesRoute = require('./api/routes/volcano.routes');

mongoose.Promise = global.Promise;

mongoose.connect(
  dburi,
  {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false,
    useCreateIndex: true,
  },
).then(
  () => {
    console.log('Connected to mongoDB');
  },
  (err) => console.log('Error connecting to mongoDB', err),
  { useNewUrlParser: true }
);


//Express app
const app = express();

app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: false }));
app.use('/api/vulcanoes', volcanoesRoute);
app.listen(port, () => {
  console.log(`running at port ${port}`);
});

路线文件:

const express = require('express');
const volcanoController = require('../controllers/volcanoController');
const router = express.Router();

router.get('/getallvulcanoes', volcanoController.getAllVolcanoes);

module.exports = router;

Controller 档案:

const VolcanoSchema = require('../models/volcano.models');

const getAllVulcanoes = (req, res) => {
    VolcanoSchema.find((err, results) => {
      if (err) {
        console.log(err);
        res.status(500).json({message: err});
      } else {
        res.status(200).json(results);
      }
    });
  };

  module.exports = {getAllVolcanoes};

Model 文件

const mongoose = require('mongoose');

const VolcanoSchema = new mongoose.Schema({
    Volcano_name:{
        type: String,
    },
    Country:{
        type: String,
    },
    Type:{
        type: String,
    },
    Latitude:{
        type: Number,
    },
    Longtitude:{
        type: Number,
    },
    Elevation:{
        type: Number,
    },
});

module.exports = mongoose.model('Volcano', VolcanoSchema);

问题是我有一个工作示例,但大部分代码都已损坏......但它的响应总是给我这个

请求示例

如果有人指出我做错了什么,那就太好了

编辑:我为我的数据库切换到 postgresql 希望这会起作用

您应该修复 Controller( VulcanoSchema.find需要一个空的 object 作为参数):

Controller 档案:

const VulcanoSchema = require('../models/vulcano.models');

const getAllVulcanoes = (req, res) => {
  VulcanoSchema.find({}, (err, results) => {
    if (err) {
      console.log(err);
      res.status(500).json({message: err});
    } else {
      res.status(200).json(results);
    }
  });
};

module.exports = {getAllVulcanoes};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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