Wednesday, 7 June 2017

Empty [ ] response from mongoDB a result of Node.js express get function?

I am getting an empty [ ] json when I try to connect localhost:3000/api/books however as you can see I made it same with genre.js. The mongoDB collections genres and books given in pictures. Thanks in advance.

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

// importing modules
Book = require('./models/book');
genre = require('./models/genre');
// connect to Mongoose

mongoose.connect('mongodb://localhost/bookstore');
var db = mongoose.connection;

app.get('/',function(req, res){
        res.send('Please use /api/books or /api/genres');


});

//getting genres
app.get ('/api/genres',function(req,res){   
    genre.getGenres(function(err,genres){
    if(err){
        throw err;
    }
    res.json(genres);
    })
});


app.get ('/api/books',function(req,res){   
    Book.getBooks(function(err,books){
    if(err){
        throw err;
    }
    res.json(books);
    })
});



app.listen(3000);
console.log('Running on port 3000... ' );

Here is my book.js file

var mongoose = require('mongoose');


var bookSchema = mongoose.Schema({
    title:{
            type:String,
            required:true
    },
    genre:{
            type:String,
            required:true

    },
    description:{
            type:String

    },
    author:{
            type:String


    },
    publisher:{
            type:String

    },
    pages:{
        type:String
    },
    image_url:{
        type:String
    },
    buy_url:{
        type:String
    },
    create_date:{
        type:Date,
        default:Date.now

    }

});

var Book = module.exports = mongoose.model('Book',bookSchema);

// Get books

module.exports.getBooks = function(callBack,limit){
Book.find(callBack).limit(limit);
};

And here is my genre.js file

var mongoose = require('mongoose');

// Genre Schema

var genreSchema = mongoose.Schema({
    name:{
            type:String,
            required:true
    },
    create_date:{
        type:Date,
        default:Date.now

    }

});

var genre = module.exports = mongoose.model('genre',genreSchema);

// Get genres

module.exports.getGenres = function(callBack,limit){
genre.find(callBack).limit(limit);
};

mongoDB collections and json content

collections in mongoDB content of the collections in JSON format



via Ordinaryus

No comments:

Post a Comment