0

I have am building an app in react and using node for my backend, which in turn connects to a cloud mongodb instance. The data is retrieved successfully from the database and logs to the console, but the returned result is showing as undefined. I am confused as to why and cant seem to solve it. here is the function in mongodb 'utils' to retrieve the data

exports.getUserByUidDb = async function (uid){
    try{
        const client = db.getDbClient()
        await client.connect()
        const ark = client.db('ark');
        const usersColl = ark.collection('users')
        console.log(`getting user by uid: ${uid}`)
        query = { "uid": uid }
        await usersColl.findOne(query).then(result => {
            if (result){
                console.log("user found. result below")
                console.log(result)
                return result
            }
            else{
                return None
            }
        }) 
    }    
    catch (err){
       console.log(`Error: ${err}`)
   }
}

and here is the login route in 'users.js'

var express = require('express');
var router = express.Router();
var dbUtils = require('./mongodb/utils');

const login = async (req) => {
   var user = {}
   // const result = await dbUtils.getUserByUidDb(req.body.uid)
   dbUtils.getUserByUidDb(req.body.uid).then(result => {
      console.log("user obtained, below")
      console.log(result)
      if(result){
         console.log("user found")
         user = {
            uid: result.uid,
            email: result.email,
            emailVerified: result.emailVerified,
            storageQuota: result.storageQuota,
            createdAt: result.createdAt,
         }
         console.log("returning existing user (below")
         console.log("Existing user")
         return user
      }else{
            console.log("no user found, creating a new one")
               user = {
               uid: req.body.uid,
               email: req.body.email,
               emailVerified: false,
               storageQuota: 0,
               createdAt: new Date()
            }
            dbUtils.saveUserDb(user)
            return user
         }
   })   
}

router.post('/login', function(req, res){
   login(req).then(result => {
      console.log("result:")
      console.log(result)
      res.json({'user': result})
   })
});

router.post('/logout', function(req, res){
   res.send('logged out');
});

module.exports = router;

and here is my console.log on trying to login

[nodemon] starting `node src/index.js`
result:
undefined
getting user by uid: 1kUXYYw1kaMPZxCs3jftjk3z7nC2
user found. result below
{
  _id: new ObjectId("61f6db61d47bce3577ac5f66"),
  uid: '1kUXYYw1kaMPZxCs3jftjk3z7nC2',
  email: 'leerobinson1984@gmail.com',
  emailVerified: false,
  storageQuota: 0,
  createdAt: 2022-01-30T18:39:29.411Z
}
user obtained, below
undefined
no user found, creating a new one
Trying to save user with uid: 1kUXYYw1kaMPZxCs3jftjk3z7nC2
user exists
Cannot Save User

I thought using the 'then' keyword would mean that code following would not execute until after the promise has resolved (or rejected), but it seems to be executing straight away.

What am I doing wrong?

help appreciated as always

HubertBlu
  • 747
  • 1
  • 7
  • 20
  • 1
    Your `getUserById` function doesn't return a value, of course, which is what the marked duplicate question will discuss in detail. I think many people get confused when they see the `return` inside the lambda thinking that it will somehow return the value all the way back to the outer function, but it does not. So don't feel bad for making the mistake. – Wyck Feb 03 '22 at 16:25

1 Answers1

0

Because you use the return inside the then method. You need to assign the result in a variable and then return the value, like this:

const result = await usersColl.findOne(query);
// All your stuff (logging etc.)
return result;
fdisotto
  • 95
  • 2
  • 7