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