Reputation: 5
Currently trying to get one user's data from my MongoDB database. But the function results in receiving undefined.
function getIntro(req){
user.findOne({ id: req },function (err, person) {
if (err){
console.log(err)
}
else{
console.log(person)
return person
}
})}
The console.log(person) provides me with the expected data so I'd assume that the return also has that data within.
The problem I am running into is where this function resolves to the console.log here comes out as undefined.
}
function getVoiceInfo(userID){
var user = userController.getIntro(userID);
console.log('here is the user ' + user)
voice(user)
}
Any help to point me in the correct direction would be amazing.
Upvotes: 0
Views: 132
Reputation: 721
Your getIntro
has an error, you can not return a person
in a callback function.
One of the approaches you can use is async/await
.
So make your functions getInvoiceInfo
and getIntro
async
and call getIntro
with await
async function getIntro(req){
try{
let person = await user.findOne({ id: req });
return person;
} catch (err) {
console.log(err)
}
}
async function getVoiceInfo(userId) {
var user = await userController.getIntro(userID);
console.log('here is the user ' + user)
voice(user)
}
You can use callbacks also, but not the way you did. And for the callback approach (as @Mohammad says) more code is needed.
Upvotes: 1