user2185427
user2185427

Reputation: 1

return value is null in node.js with mongoose

I am using node.js with mongoose. The problem i am facing is i am getting newModifier1 printed but outside that function the value is null.

Here is my code:

// Find userSchema

newModifier1 = "";

exports.findModifier = function(modifierName){
  modifierModel.find({'name' : modifierName},function(err,result){
    if(err){
      console.log("Error : "+err);
      throw err;
    }
    else{
      newModifier1 = result;
    //  console.log("Modifier is searched successfully : "+newModifier1);
    }
    console.log("Modifier is searched successfully1 : "+newModifier1);
  });
  // newModifier1=temp;
  return newModifier1; // it takes newModifier1 = "" value here
}

Any ideas what the problem could be?

Upvotes: 0

Views: 406

Answers (2)

TheHippo
TheHippo

Reputation: 63139

This is what is happening:

// this is "global" an would be weirdly overwritten
// if function is called multiple times before finishing
newModifier1 = "";

exports.findModifier = function(modifierName){

    // TIMESTAMP: 0

    modifierModel.find({'name' : modifierName},function(err,result){

        // TIMESTAMP: 2

        if(err){
            console.log("Error : "+err);
            throw err;
        }
        else{
            newModifier1 = result;
        //  console.log("Modifier is searched successfully : "+newModifier1);
        }
        console.log("Modifier is searched successfully1 : "+newModifier1);
    });

    // TIMESTAMP: 1

    return newModifier1; // it takes newModifier1 = "" value here
}

I added some notes, when what is happening. As you can see and because of the async nature of node.js you return the value before you get a result back from the database.

You need familiarize yourself with the async flow and callback function.

Pass a callback function to findModifier and wait for the database to return a result.

Upvotes: 1

idursun
idursun

Reputation: 6335

modifierModel.find runs asynchronously and probably findModifier method is returning before the callback of find method executes. Although you see it being printed out what is returned from the method is en empty string anyway. You can use a library like async.

Upvotes: 0

Related Questions