Your issue is that you're not waiting for your getLastId()
to actually return since it is async. Since it is async, while getLastId()
is still working, your code has already moved on to creating a new Transaction
where newId
is undefined
since nothing has been returned. So you need to place your code dependent on newId
into the callback of your Transaction.findOne()
or pass in a callback to getLastId()
.
Just to note, your addtransaction
function should take a callback function as well so you can return the outcome of newTransactions.save()
to the called in an asynchronous way. I did not do this in the below code examples since I do not know how your other code is structured.
I would also say that Approach #1 below is the preferable one since its less code, doesn't involve defining getLastId()
everytime addtransaction()
is called and it is has less callbacks than Approach #2.
Approach #1, place logic in Transactions.findOne()
function addtransaction(user_id, status, amount, date, description) {
Transactions.findOne({}, {}, { sort: { '_id' : -1 } }).lean().exec(function(err, lastTrans) {
var newId = err ? 1 : (parseInt(lastTrans.id) + 1);
var newTransactions = new Transactions({
id : newId,
user_id : user_id ,
status : status ,
amount : amount ,
date : date ,
description : description
});
return newTransactions.save();
});
}
Approach #2, Pass in Callback
/* function for add transaction */
function addtransaction(user_id,status,amount,date,description){
var saved = "";
function getLastId(callback){
Transactions.findOne({}, {}, { sort: { '_id' : -1 } }).lean().exec(function(err, lastTrans) {
if (err) {
return callback(null, 1);
} else {
return callback(null, parseInt(lastTrans.id) + 1);
}
});
}
getLastId((err, newId) => {
var newTransactions = new Transactions({
id : newId,
user_id : user_id ,
status : status ,
amount : amount ,
date : date ,
description : description
});
return newTransactions.save();
});
}/* end function */
Its also worth noting that assigning return data directly from a function that is async isn't the proper way to construct asynchronous functions in Node.js. See this answer for the proper way to construct these types of functions.