Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS and node-mongodb-native

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...

like image 317
user369680 Avatar asked Jun 17 '10 18:06

user369680


People also ask

What is node MongoDB native?

The official MongoDB Node. js driver allows Node. js applications to connect to MongoDB and work with data. The driver features an asynchronous API which allows you to interact with MongoDB using Promises or via traditional callbacks.

Is MongoDB compatible with node js?

All features are supported. The Driver version will work with the MongoDB version, but not all new MongoDB features are supported.

What is the difference between MongoDB and node JS?

MongoDB is a widely used NoSQL database. The ability to store data in several formats makes MongoDB a beneficial tool for managing large amounts of data. On the other hand, Nodejs is a well-known runtime environment that assists in executing JavaScript code outside the browser.

What is MongoDB native driver?

The native MongoDB driver for Node. JS is a dependency that allows our JavaScript application to interact with the NoSQL database, either locally or on the cloud through MongoDB Atlas.


1 Answers

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!

like image 177
foobar Avatar answered Oct 06 '22 00:10

foobar