kohli kohli - 2 months ago 11
Node.js Question

Get the return value from mongoose call back function Node.js

I have written a function like this

function create(data, res){

var history= new historyData({
owner: data
});

historyData.save(function(err, historyData) {


//To identify the error
if (err) {


console.log(err);
}

//If no error pass the team details to databsae
else {

return historyData.id;

}
});
}


and I'm trying to get the return value like this

var history = create("saddsa", res);


but it gives
undefined
error

I want to get the
id
of the created collection and pass it to another function?

Answer

Try to return a callback and get that value

function create(data, res, callback) {

  var history = new historyData({
    owner: data
  });

  historyData.save(function(err, historyData) {
    //To identify the error
    if (err) {
      console.log(err);
      callback(err)
    }

    //If no error pass the team details to databsae
    else {
      return callback(null,historyData.id);

    }
  });
}

 // call your function like this    
  create("saddsa", res,function(err,result){
      if(!err){
        console.log(result)
      }
    });