NodeJS - 服务不能使用mongo -

时间:2016-08-02 09:29:41

标签: node.js mongodb express service

在解释我的问题之前,这是我的架构:

1 - server is running, getting request and storing data
2 - a service - called process_runner.js - is running on a 2nd terminal

服务的目的是从我的数据库中获取数据以执行某些功能。

这是服务:process_runner.js

// all needed requires
/// ...
//


mongoose.connect(config.database);

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'Error connecting to MongoDB:'));
db.once('open', function() {
  console.log("Connected to MongoDB");
  try {
    run();
  } catch (e) {
    console.log (e);
  }

});


 //...

 var run = function() {

console.log("Start processes manager");

var taken = false;
while(true) {
  console.log ("iteration")

  if (taken == false) {
    taken = true;

    console.log("go");
    // Then I want to get my capacities
    // when the call below is done, nothing appends and the loop continues

    Capacity.find({} , function(err, capacities) {
      console.log ("OK CONTINUE");
      // ...
      // next of the events
   });
 ... }...

(循环有一个sleep(1)

这是输出:

Connected to MongoDB
Start processes manager
iteration
go
iteration
iteration
iteration
...

所以,在'go'消息之后我需要收到'OK CONTINUE'消息,其余的代码将会执行,

但是当Capacity.find({} , function(err, capacities) {.... 完成,没有任何附加,循环继续(err

中没有任何内容

任何想法?

1 个答案:

答案 0 :(得分:1)

这里的问题在于 var jsonFileArr = JSON.parse(data); //Parse the data from JSON file var foundId = jsonFileArr.findIndex(function (obj){ // Checks if the POST request have the same id as JSON file return obj.id == POST.id; }); if (foundId >= 0) { jsonFileArr[foundId] = { id: POST.id, name: POST.name, phone: POST.phone, } } 循环。 由于while(true)是单线程的,因此您只是阻止执行循环,这不允许执行数据库调用。

只需删除无限循环,并在成功执行后调用相同的函数:

Node.js