Home > Enterprise >  MongoDB Atlas: Cannot GET from API
MongoDB Atlas: Cannot GET from API

Time:01-07

I developed a simple API that is supposed to GET data from MongoDB Atlas. Unfortunately, if I directly hit the browser or use Postman, I am getting an error:

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 (Contains room schema):

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;

My Atlas looks like this:

DB Screenshot

I have ensured from Network Access that all IP connections are allowed (0.0.0.0/0).

This is my first API so I reckon I'm missing something basic. Can anybody help me figure this out?

Update 1: By adding "/" in app.use, the error is gone but I'm getting empty response from the DB:

{
    "rooms": []
}

Update 2: enter image description here

After ensuring column names in model and DB are synchronised, still the response I'm getting is empty.

CodePudding user response:

The problem is with database URL. By default MongoDB gives the URL of "test" database. Updating the database name fixed the problem for me.

CodePudding user response:

Here:

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

I think you need to prefix the path with a / like so:

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

See the Express documentation for path examples.

  •  Tags:  
  • Related