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.
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
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.