Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Why is this query returning the database object?

Why is this query returning the database object?

Problem

mongo.connect(mongostr, {}, function(error, db){ 
    var mycoll = db.collection("newuser"); 
    mycoll.find({'userID':12345}, 
                {'userID':true}, 
                function(err, value) {
                    console.log(value);
                }); 
});

I've added a test collection to mongoDB, I know for a fact it's there. I know for a fact that exact Query returns what I want (tested it myself in mongoHQ panel). mongo object works fine. Unfortunately the docs don't have an example, so I can't see what I'm doing wrong.

When the query runs I get a console dump of the db object:

 { db:     { databaseName: 'appxxxxxxx',
      serverConfig: 
       { host: 'staff.mongohq.com',
         port: 10096,
         options: {},
         internalMaster: true,
         connected: true,
         poolSize: 1,
         ssl: false,
         slaveOk: undefined,
Problem courtesy of: dsp_099

Solution

db.collection is an async call. You are accessing it in a synchronous fashion.

var mycoll = db.collection("newuser");

Try this:

mongo.connect(mongostr, {}, function(error, db){ 
    var mycoll = db.collection("newuser", function(err,collection){
             collection.find({'userID':12345}, 
                {'userID':true}, 
                function(err, value) {
                    console.log(value);
                }); 
    });
});
Solution courtesy of: Rajat

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Why is this query returning the database object?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×