回调函数意外运行

时间:2014-05-03 17:37:57

标签: node.js callback asynccallback

我在下面写了一个小代码,并在评论中解释了问题。问题在于创建集合时使用粗体回调函数。创建集合时出错,一旦创建集合的主函数结束,消息就会显示,但消息会随机出现,如下面的输出所示:

在标有问号的行上称为意外。我在node.js和mongoDB环境中运行这个js文件。

感谢。

   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);
    }
    });

以下是输出。 我们已经连接了!

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

1 个答案:

答案 0 :(得分:0)

您应该在node的回调中处理db.createCollection集合:

更新:运行此代码:

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);
  }
});