简体   繁体   中英

Mongoose, NODE JS returns undefined but the correct data is collected within the findOne

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM