来自mongoDB的empty []响应是Node.js表达get函数的结果吗?

时间:2017-06-07 10:36:03

标签: node.js mongoose

当我尝试连接localhost:3000 / api / books时,我得到一个空的[] json但是你可以看到我和genre.js一样。 mongoDB集合类型和图片中给出的书籍。提前致谢。

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... ' );

这是我的book.js文件

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);
};

这是我的genre.js文件

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集合和json内容

collections in mongoDB content of the collections in JSON format

1 个答案:

答案 0 :(得分:0)

尝试重写路由方法,然后将集合名称添加到模型中。 假设您的收藏名称为 Book 。它应该看起来像这样:

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