How to access a preexisting collection with Mongoose?

Mongodbnode.jsExpressMongoose

Mongodb Problem Overview


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.connect('mongodb://localhost/test');
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

Mongodb Solutions


Solution 1 - Mongodb

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

Solution 2 - Mongodb

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 } ]

Solution 3 - Mongodb

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

});

Update 2022

If you get an MongoInvalidArgumentError: The callback form of this helper has been removed. error message, here's the new syntax using async/await:

const mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/productsDB');

const connection = mongoose.connection;

connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', async function () {

  const collection  = connection.db.collection("Products");
  collection.find({}).toArray(function(err, data){
      console.log(data); // it will print your collection data
  });

});

Solution 4 - Mongodb

I had the same problem and was able to run a schema-less query using an existing Mongoose connection with the code below. I've added a simple constraint 'a=b' to show where you would add such a constraint:

var action = function (err, collection) {
    // Locate all the entries using find
    collection.find({'a':'b'}).toArray(function(err, results) {
        /* whatever you want to do with the results in node such as the following
             res.render('home', {
                 'title': 'MyTitle',
                 'data': results
             });
        */
    });
};

mongoose.connection.db.collection('question', action);

Solution 5 - Mongodb

Are you sure you've connected to the db? (I ask because I don't see a port specified)

try:

mongoose.connection.on("open", function(){
  console.log("mongodb is connected!!");
});

Also, you can do a "show collections" in mongo shell to see the collections within your db - maybe try adding a record via mongoose and see where it ends up?

From the look of your connection string, you should see the record in the "test" db.

Hope it helps!

Solution 6 - Mongodb

Something else that was not obvious, to me at least, was that the when using Mongoose's third parameter to avoid replacing the actual collection with a new one with the same name, the new Schema(...) is actually only a placeholder, and doesn't interfere with the exisitng schema so

var User = mongoose.model('User', new Schema({ url: String, text: String, id: Number}, { collection : 'users' }));   // collection name;
User.find({}, function(err, data) { console.log(err, data, data.length);});

works fine and returns all fields - even if the actual (remote) Schema contains none of these fields. Mongoose will still want it as new Schema(...), and a variable almost certainly won't hack it.

Solution 7 - Mongodb

Go to MongoDB website, Login > Connect > Connect Application > Copy > Paste in 'database_url' > Collections > Copy/Paste in 'collection' .

var mongoose = require("mongoose");
mongoose.connect(' database_url ');
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function () {
  conn.db.collection(" collection ", function(err, collection){
    collection.find({}).toArray(function(err, data){
      console.log(data); // data printed in console
    })
  });
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontheabrahamView Question on Stackoverflow
Solution 1 - MongodbcalvinfoView Answer on Stackoverflow
Solution 2 - MongodbMichael TaufenView Answer on Stackoverflow
Solution 3 - MongodbLeo RibeiroView Answer on Stackoverflow
Solution 4 - MongodbWill NathanView Answer on Stackoverflow
Solution 5 - MongodbbusticatedView Answer on Stackoverflow
Solution 6 - MongodbBartView Answer on Stackoverflow
Solution 7 - Mongodbrttss_sahilView Answer on Stackoverflow