F4Ke F4Ke - 1 year ago 48
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 :

// all needed requires
/// ...


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

// 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

this is the output :

Connected to MongoDB
Start processes manager

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

any ideas ?

Answer Source

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