6

Just getting started with node, and trying to get the mongo driver to work. I've got my connection set up, and oddly I can insert things just fine, however calling find on a collection produces craziness.

var db = new mongo.Db('things', new mongo.Server('192.168.2.6',mongo.Connection.DEFAULT_PORT, {}), {});

db.open(function(err, db) {
    db.collection('things', function(err, collection) {
//          collection.insert(row);
        collection.find({}, null, function(err, cursor) {
            cursor.each(function(err, doc) {
                sys.puts(sys.inspect(doc,true));
            });
        });

    });
});

If I uncomment the insert and comment out the find, it works a treat. The inverse unfortunately doesn't hold, I receive this error:

        collection.find({}, null, function(err, cursor) {
            ^
TypeError: Cannot call method 'find' of null

I'm sure I'm doing something silly, but for the life of me I can't find it...

2
  • I think this means you get an error. Can you check the 'err' value? Commented Jun 18, 2010 at 5:21
  • Also, I think you use when you use new mongo.Db('things'... 'things' is DB name not a collection. I'm not sure that this cause the problem or not Commented Jun 18, 2010 at 5:27

2 Answers 2

9

I got the same thing just now. I realized that db.collection is being called over and over again for some reason, so I did something like this (hacking away on your code):

    var db = new mongo.Db('things', new mongo.Server('192.168.2.6',mongo.Connection.DEFAULT_PORT, {}), {});

    var Things;    

    db.open(function(err, db) {
        db.collection('things', function(err, collection) {
            Things = Things || collection;    
    });

   var findThings = function() {
       Things.find({}, null, function(err, cursor) {
           cursor.each(function(err, doc) {
               sys.puts(sys.inspect(doc,true));
           });
       });
   }

I realize you asked this 9 months ago. Hope this grave diggin still helps someone. Good luck!

Sign up to request clarification or add additional context in comments.

Comments

-2

try to call collection.save() after your insert to flush your row.

take a look at http://www.learnboost.com/mongoose/

"Currently Mongoose only supports manual flushing of data to the server."

1 Comment

Mongoose != node-mongodb-native

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.