F4Ke F4Ke - 4 months ago 11
Node.js Question

NodeJS - Service can't use mongo -

Before explaining my issue, this is my architecture :

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


the point of the service is to fetch data from my database to execute some functions.

this is the service :
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
});
... }...


(the loop has a
sleep(1)
)

this is the output :

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


so, after the 'go' message I need to recevied the 'OK CONTINUE' message, and the rest of the code will execute,

but when the
Capacity.find({} , function(err, capacities) {....

is done, nothing appends and the loop continue (nothing in the
err
)

any ideas ?

Answer

The problem here lies in the while(true) loop. As Node.js is single-threaded you're just blocking the execution loop, which doesn't allow your database call to be executed.

Simply remove the infinite loop and call the same function upon successful execution:

var run = function() {
  Capacity.find({} , function(err, capacities) {
    //do stuff
    return run();
  });
}
Comments