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

I get an empty [] json when I try to connect localhost: 3000 / api / books, but as you can see, I did it with genre.js. The genres and books of the mongoDB collections are shown in the photographs. Thank you 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 collections in JSON format

+3


source to share





All Articles