0

There is a small code i have written below and issue is explained within comments. Problem is with the bold callback function while creating the collection. There is an error while creating the collection and the message should be displayed as soon as the main function for creating the collections is ending but message appears randomly as seen in the output below:

It is called unexpected on line marked with question mark. I am running this js file on node.js and mongoDB environment.

Thanks.

   var mongo = require("mongodb");
    var Db = mongo.Db;
    var mongoC = mongo.MongoClient;
    var assert = require('assert');

    mongoC.connect("mongodb://localhost:27017/social", {
        native_parser: true
    }, function (err, db) {
        if (!err) {
            console.log("We are Connected!\n");

            //creating the Collection
            db.createCollection("node", {
                strict: true
            }, function (err, coll) {
                if (!err) {
                    console.log("*********Collection Created Succesfully*********");
                    console.log("Collection created Successfully\n" + JSON.stringify(coll) + "\n-------------------\n");
                }
    else{
    console.log("Cannot create Collection because " + err);
    }
    });
    //Collection created now


    console.log("*********************************inserting documents in the selected collection***********************");


    var coll = db.collection('node');
    var doc1 = {"name":"doc1","age":26};
    var manydocs = [{"name":"doc2","age":45},{"name":"doc3","age":19}];

    //coll.insert(doc1,{w:1},function(err,result){if(err){console.log("Error while inserting doc1 " + err);}else{console.log(result);}});
    //coll.insert(manydocs,{w:1},function(err,result){if(err){console.log("Error while inserting manydocs " + err);}});
    console.log("***************************documents are now updated successfully***********************************");


    console.log("*******************Now let us update the documents*******************");
    var query = {"name": "doc1"};
    var update= {$set : {"age":86}};
    //coll.update(query,update,function(err,result){if(!err){console.log(result + "'s age has been successfully update to " + result);}});
    console.log("***************Docments updated");


    console.log("*******************Querying the items**************************");

    coll.find().each(function(err,myDoc){console.dir(myDoc);console.dir("hey");});
    //coll.findOne(query,function(err,result){});

    var stream = coll.find(query).stream();
    stream.on("data",function(item){console.log(item._id);});
    stream.on("end",function(){});



    }
    else {
    console.log("Cannot connect because : " + err);
    }
    });

Below is the output. We are Connected!

*********************************inserting documents in the selected collection***********************
***************************documents are now updated successfully***********************************
*******************Now let us update the documents*******************
***************Docments updated
*******************Querying the items**************************
Cannot create Collection because Error: Collection node already exists. Currently in strict mode.
logeekal
  • 525
  • 4
  • 13

1 Answers1

0

You should work on node collection inside the db.createCollection's callback:

UPDATE: run this code:

var mongo = require("mongodb");
var Db = mongo.Db;
var mongoC = mongo.MongoClient;
var assert = require('assert');

mongoC.connect("mongodb://localhost:27017/social", {
  native_parser: true
}, function (err, db) {
  if (!err) {
    console.log("We are Connected!\n");

    //creating the Collection
    db.createCollection("node", {
      strict: true
    }, function (err, coll) {
      if (!err) {
        console.log("*********Collection Created Succesfully*********");
        console.log("Collection created Successfully\n" + JSON.stringify(coll) + "\n-------------------\n");

        //Collection created now


        console.log("*********************************inserting documents in the selected collection***********************");

        var doc1 = {
          "name": "doc1",
          "age": 26
        };
        var manydocs = [{
          "name": "doc2",
          "age": 45
        }, {
          "name": "doc3",
          "age": 19
        }];

        //coll.insert(doc1,{w:1},function(err,result){if(err){console.log("Error while inserting doc1 " + err);}else{console.log(result);}});
        //coll.insert(manydocs,{w:1},function(err,result){if(err){console.log("Error while inserting manydocs " + err);}});
        console.log("***************************documents are now updated successfully***********************************");


        console.log("*******************Now let us update the documents*******************");
        var query = {
          "name": "doc1"
        };
        var update = {
          $set: {
            "age": 86
          }
        };
        //coll.update(query,update,function(err,result){if(!err){console.log(result + "'s age has been successfully update to " + result);}});
        console.log("***************Docments updated");


        console.log("*******************Querying the items**************************");

        coll.find().each(function (err, myDoc) {
          console.dir(myDoc);
          console.dir("hey");
        });
        //coll.findOne(query,function(err,result){});

        var stream = coll.find(query).stream();
        stream.on("data", function (item) {
          console.log(item._id);
        });
        stream.on("end", function () {});

      } else {
        console.log("Cannot create Collection because " + err);
      }
    });
  } else {
    console.log("Cannot connect because : " + err);
  }
});
wachme
  • 2,327
  • 20
  • 18
  • if I get the same output in that case that will be great but i what I am getting right now is very unexpected. Does it mean that it is taking time in error IO and in the meantime node executes other codes. – logeekal May 03 '14 at 19:18
  • Please run the code above and tell me what's the output. This code is asynchronous, so you cannot predict order of operations being invoked – wachme May 03 '14 at 19:30