Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Francesco Di Vito
Francesco Di Vito
4,502 Points

Rest Services NodeJS + MongoDB empty array

Hi att all. I'm developing a basic rest service with nodejs + mongo db, so i 'm using mongoose driver for query on db. Now this is the code to start server:

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

Genre = require('./models/genre');

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

app.get('/', function(req, res){ res.send('Please call end poitn /api/....'); });

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

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

and this is the model: 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); }

Now when i test a rest service with postman i recive a ampty array [], whitout error. But in my db the collection generes have 2 elements.

Any help is great Thanks

1 Answer

Seth Kroger
Seth Kroger
56,413 Points

Mongoose's Model.find() requires a first parameter with the query conditions. Also passing the callback to find will cause it to execute immediately before limit gets attached to it. Try Genre.find({}).limit(limit).exec(callback) or Genre.find({}, null, {limit: limit}, callback)

http://mongoosejs.com/docs/queries.html http://mongoosejs.com/docs/api.html#model_Model.find