【问题标题】:MongoDB Atlas: Cannot GET from APIMongoDB Atlas:无法从 API 获取
【发布时间】:2022-01-05 21:08:03
【问题描述】:

我开发了一个简单的 API,可以从 MongoDB Atlas 获取数据。不幸的是,如果我直接点击浏览器或使用 Postman,则会出现错误:

Cannot GET /api/rooms/getallrooms

server.js

const express = require('express');
const app = express();

const dbConfig = require('./db');
const roomsRoute = require('./routes/roomsRoute');

app.use('api/rooms', roomsRoute);

const port = process.env.PORT || 5001;

app.listen(port, () => {
    console.log(`Server started on port ${port} :)`);
});

roomsRoute.js:

const express = require('express');
const router = express.Router();

const Room = require('../models/rooms');

router.get('/getallrooms', async (req, res) => {
    try {
        const rooms = await Room.find({});
        return res.json({rooms});
    } catch (error) {
        return res.status(400).json({message: error});
    }
});

module.exports = router;

rooms.js(包含房间架构):

const mongoose = require('mongoose');

const roomSchema = mongoose.Schema({
    name : {
        type: 'String',
        required: true,
    },
    capacity : {
        type: 'number',
        required: true,
    },
    contact : {
        type: 'number',
        required: false,
    },
    type : {
        type: 'String',
        required: true,
    },
    imageURLs : [],
    currentBookings : [],
    description : {
        type: 'String',
        required: false,
    },
    rentPerDay : {
        type: 'number',
        required: true,
    }
},{
    timestamps: true,
});

const roomModel = mongoose.model('rooms', roomSchema);

module.exports = roomModel;

我的地图集如下所示:

我已通过网络访问确保允许所有 IP 连接 (0.0.0.0/0)。

这是我的第一个 API,所以我认为我缺少一些基本的东西。谁能帮我解决这个问题?

更新 1: 通过在 app.use 中添加“/”,错误消失了,但我得到了来自 DB 的空响应:

{
    "rooms": []
}

更新 2:

确保模型和数据库中的列名同步后,我得到的响应仍然是空的。

【问题讨论】:

    标签: node.js mongodb api rest express


    【解决方案1】:

    这里:

    app.use('api/rooms', roomsRoute);
    

    我认为您需要在路径前加上 / 前缀,如下所示:

    app.use('/api/rooms', roomsRoute);
    

    请参阅 path examples 的 Express 文档。

    【讨论】:

    • 谢谢@Montgomery Watts,通过添加“/”错误消失了,但现在我得到空响应{“rooms”:[]}。你能帮忙吗?
    • 猫鼬模式中的字段名称需要与数据库中的内容相匹配。 @Ashar
    • 我会验证的。非常感谢。
    • 我确保数据库和房间模型中的所有名称都是同步的,但我仍然得到空响应。
    • 您声明field types 的方式可能很重要。 'string''String' 的行为可能不同。 @Ashar
    【解决方案2】:

    问题出在数据库 URL 上。默认情况下,MongoDB 提供“测试”数据库的 URL。更新数据库名称为我解决了这个问题。

    【讨论】:

      猜你喜欢
      • 2019-12-22
      • 2019-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 2019-10-31
      相关资源
      最近更新 更多