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
Try rewriting the routing method and add your collection name to your model. let say that your collection name is called Book . It should look like this:
var Book = module.exports = mongoose.model('Book', bookSchema, 'Book');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.