Node,MongoClient和Mongodb,无限循环不执行

时间:2016-10-05 20:23:23

标签: javascript node.js mongodb

我有一些代码已经放在一起并且有点了解。随着我的进展,我正在建立自己的知识。我试图将一些随机数据分配给一个工作正常的变量,然后通过使用无限循环和睡眠函数将其插入数据库(我听说睡眠不是最好的方法,但代码不一定非常完美)。数据插入一次,然后重新分配变量,但它不会插入数据库。

function main() {      
//import mongodb and assign it to variable mongodb
var mongodb = require('mongodb');
//use mongodb variable to assign the Mongo Client to te vaariable
MongoClient
var MongoClient = mongodb.MongoClient;
//Connection URL. This is where your mongodb server is running.
var url = 'mongodb://localhost:27017';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
if (err) {
  while (true) {
    console.log('Assign var');
    //Create an entry for db
    var tempvalue = {
      'time': Date.now(),
      'type': 'Temperature',
      'location': 1,
      'value': getRandomInt(25, 28)
    };
    console.log(tempvalue);
    sensorcollection.insert({
      'time': Date.now(),
      'type': 'Temperature',
      'location': 1,
      'value': getRandomInt(25, 28)
      },
      function (err, result) {
        if (err) {
          console.log(err);
        } else {
          console.log('The documents inserted with "_id" are:', result);
        }
      });
    //console.log('inserted');
    sleepFor(10000);

    //console.log('where am i');
  }
}
});
}

main();

任何帮助都会非常感激。

2 个答案:

答案 0 :(得分:0)

连接后的第一行是

if (err)

因此,只有当您的连接失败时,您才会尝试插入? 不应该像

那样
if (!err)

答案 1 :(得分:0)

  • 首先使用if(err)来执行代码,这意味着只有在与DB的连接失败时才插入文档。
  • 其次你使用了似乎不存在的sensorcollection变量,你应该让MongoDB为你提取集合。
  • 第三,你使用sleepFor不是node.js函数,而是使用setTimeout。

你应该看看node.js模型,以了解什么是错误的。

请改为尝试:

function main() {      
    //import mongodb and assign it to variable mongodb
    var mongodb = require('mongodb');
    //use mongodb variable to assign the Mongo Client to te vaariable
    var MongoClient = mongodb.MongoClient;
    //Connection URL. This is where your mongodb server is running.
    var url = 'mongodb://localhost:27017';
    // Use connect method to connect to the Server
    MongoClient.connect(url, function(err, db) {
        if (!err) {
            //you need to fetch the MongoDB collection object
            db.collection('sensorcollection', function(err, col) {
                if(err)
                    return console.error('Error while fetching collection', err)

                //void function() {}() declare a function add call it, you can do the same with main()
                void function addStat() {
                    var tempvalue = {
                        'time': Date.now(),
                        'type': 'Temperature',
                        'location': 1,
                        'value': getRandomInt(25, 28)
                    };

                    col.insert(tempvalue, function(err, result) {
                        if(err)
                            console.log(err)
                        else {
                            console.log('The documents inserted with "_id" are:', result);
                            setTimeout(addStat, 10000) //wait 10000 before inserting
                        }
                    })
                }()
            })
        }
        else {
            console.error('MongoDB error', err)
        }
    });
}

main();