0

I have a database on mongodb named 'abode' and I am trying to make an API where I can use this data to be displayed on a web app. The file structure of the web app is like this.

enter image description here

app.js

const http = require('http'); //Core Module
const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path'); //Core Module
const mongoose = require('mongoose');

const app = express();
const port = 3001;

Bhk = require('./models/bhk');
//Connect to mongoose
mongoose.connect('mongodb://localhost/abode');

const db = mongoose.connection;

app.get('/api/bhk', (req, res)=>{
    Bhk.getBHK(function(err, bhk){
        if(err){throw err;}
        res.json(bhk);
    });
});

bhk.js

const mongoose = require('mongoose');

//BHK schema
const bhkSchema = mongoose.Schema({
    Name:{
        type: String,
        required: true
    },
    create_date:{
        type: Date,
        default: Date.now
    }
});

const bhk = module.exports = mongoose.model('BHK', bhkSchema);

// Get BHK
module.exports.getBHK = function(callback, limit){
    bhk.find(callback).limit(limit);
}

When I run the app it shows an empty array on my webpage. Like this enter image description here

The server starts successfully and there are no errors shown in my console as well. In the collections of my database I have a collection named - BHK. It consists of two records

{ "_id" : ObjectId("5a6d60827fad61a75bbcb5e9"), "Name" : "2BHK" }
{ "_id" : ObjectId("5a6d60b77fad61a75bbcb5ea"), "Name" : "3BHK" }

However no of these records are shown. I tried searching for various solutions of using a mongo db client, however I could not yet get the required result. I do not know where am I going wrong.

rut_0_1
  • 761
  • 1
  • 11
  • 34

1 Answers1

0

After a lot of surfing through the net and trial and error, I realized MongoDB has a convention for naming collections and databases. The collection that I had named was 'BHK', which according to its guidelines and conventions was wrong. The collection name has to be in lower case and plural which in my case I had to rename the collection to:

bhks

rut_0_1
  • 761
  • 1
  • 11
  • 34