How to access a preexisting collection with Mongoose? How to access a preexisting collection with Mongoose? express express

How to access a preexisting collection with Mongoose?


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:

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


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) {       collection.find(query).toArray(cb);   });}

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) {            console.dir(docs);        });//output: [ { _id: 4e22118fb83406f66a159da5, a: 1 } ]


You can do something like this, than you you'll access the native mongodb functions inside mongoose:

var mongoose = require("mongoose");mongoose.connect('mongodb://localhost/local');var connection = mongoose.connection;connection.on('error', console.error.bind(console, 'connection error:'));connection.once('open', function () {    connection.db.collection("YourCollectionName", function(err, collection){        collection.find({}).toArray(function(err, data){            console.log(data); // it will print your collection data        })    });});