How to access a preexisting collection with Mongoose?


I have a large collection of 300 question objects in a database test. 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 existing 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
5/28/2017 10:30:02 PM

Accepted Answer

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
11/3/2011 3:21:05 PM

Here's an abstraction of Will Nathan's answer if anyone just wants an easy copy-paste add-in function:

function find (name, query, cb) {
    mongoose.connection.db.collection(name, function (err, collection) {

simply do find(collection_name, query, callback); to be given the result.

for example, if I have a document { a : 1 } in a collection 'foo' and I want to list its properties, I do this:

find('foo', {a : 1}, function (err, docs) {
//output: [ { _id: 4e22118fb83406f66a159da5, a: 1 } ]

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow