5

I am new to both Node.js and MongoDB, but I intend to create a very basic real time geolocation based web app. Here is my attempt at figuring out how Node and MongoDB interact:

var mongo = require('mongodb');

var db = new mongo.Db('test', new mongo.Server('localhost',22892, {}), {});

db.open(function(){});

db.collection('docs', function(err,collection){
    doc = {"foo":"bar"};
    collection.insert(doc, function(){});
});

I can see that this is connecting:

Thu Apr 14 15:24:12 [initandlisten] connection accepted from 127.0.0.1:46968 #26
Thu Apr 14 15:24:12 [conn26] building new index on { _id: 1 } for test.docs
Thu Apr 14 15:24:12 [conn26] done for 0 records 0secs

But it's not inserting any documents into the database. Can anyone tell me what I am doing wrong?

Thanks

2
  • which particular mongodb driver are you using? Commented Apr 14, 2011 at 20:38
  • you can refer to this link. programmerblog.net/nodejs-mongodb-tutorial Commented Jul 20, 2017 at 11:54

1 Answer 1

28
db.open(function(err, client){
    client.createCollection("docs", function(err, col) {
         client.collection("docs", function(err, col) {
             for (var i = 0; i < 100; i++) {
                 col.insert({c:i}, function() {});
             }
         });
    });
});

You forgot to do everything in your open callback. This is important otherwise your code runs before your connection to the database is open. You have to do everything asynchronous. It's also best to create the collection if it does not exist.

Take a look at the extensive examples at the github page

Now this looks like callback spaghetti so we use flowcontrol like Step to make it pretty.

Step(
    function() {
        db.open(this);
    },
    function(err, client) {
        client.createCollection("docs", this);
    },
    function(err, col) {
        for (var i = 0; i < 100; i++) {
            col.insert({c:i});
        }
    }
);
Sign up to request clarification or add additional context in comments.

Comments

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.