theabraham theabraham - 6 months ago 50
Node.js Question

How to access a preexisting collection with Mongoose?

So I have a large collection of 300

objects in a database
. I can interact with this collection easily through MongoDB's interactive shell; however, when I try to get the collection through Mongoose in an express.js application I get an empty array.

My question is, how can I access this already existant dataset instead of recreating it in express? Here's some code:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.model('question', new Schema({ url: String, text: String, id: Number }));

var questions = mongoose.model('question');
questions.find({}, function(err, data) { console.log(err, data, data.length); });

This outputs:

null [] 0


Mongoose added the ability to specify the collection name under the schema, or as the third argument when declaring the model. Otherwise it will use the pluralized version given by the name you map to the model.

Try something like the following, either schema-mapped:

new Schema({ url: String, text: String, id: Number}, 
           { collection : 'question' });   // collection name

or model mapped:

               new Schema({ url: String, text: String, id: Number}), 
               'question');     // collection name