1

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?

4
  • you can't return value from save method. Commented Sep 25, 2016 at 4:11
  • So how can i get the saved data id and pass to another function?? @AshishSuthar Commented Sep 25, 2016 at 4:12
  • you can give a callback function and get that data from there Commented Sep 25, 2016 at 4:13
  • Ok if you can give an example that will be helpful Commented Sep 25, 2016 at 4:14

2 Answers 2

1

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)
      }
    });
Sign up to request clarification or add additional context in comments.

8 Comments

are you getting value in historyData.id after saving?
yes i'm getting and in the callback functions result i'm getting the id but couldn't get it to a variable
check your historyData.id when return after saving? console.log(historyData.id)
It should work, if you get value in callback(null,historyData.id);
If you do not get error and enter in else condition put callback(null,historyData); And get that value like at calling time if (!err){ console.log(historyData)//if you get right value then access historyData.id }
|
0

replace

return historyData.id;

with

if(res) res(historyData.id);

and call

create("saddsa", function (id) { var history = id; });

1 Comment

It's not gonna work. Have you test it? Define proper callback with proper parameters(err,value)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.