Why does my database collection return "Undefined" ?

I want to set some session variables early on such as _id etc. All I am trying to do is if the user is logged in, I want to get some other details in the session. But the database query keeps returning “Undefined”. Help !
Here’s the code
if(wixUsers.currentUser.loggedIn) {
$w(“#loginButton”).label = “Logout”;
$w(“#profileButton”).show();
//$w(“#readersButton”).show();
let userId = wixUsers.currentUser.id;
session.setItem(“userId”, userId);
wixData.query(“User”).eq(“_id”, userId)
.find()
.then( (results) => {
if (results.items.length === 0) {
console.log (“IN ONREADY. NOTHIG RETURNED”);
}

   let value = results.items[0].value; 
 console.log("IN ON READY. HERE IS WHAT I GOT") 
 console.log(value); 

// userRole = useritem._id;
} )
.catch( (err) => {
let errorMsg = err;
console.log (errorMsg);
} );

}

And here is what I see in the log
Loading the code for the site. To debug this code, open masterPage.js in Developer Tools.
_partials/santa/1.2658.25/node_modules/santa-wix-code/dist/wixcode-worker.js:1 Loading the code for the site. To debug this code, open masterPage.js in Developer Tools.
wixcode-worker.js:1 Loading the code for the Home page. To debug this code, open cjg9.js in Developer Tools.
_partials/santa/1.2658.25/node_modules/santa-wix-code/dist/wixcode-worker.js:1 Loading the code for the Home page. To debug this code, open cjg9.js in Developer Tools.
maze:1 The resource https://static.wixstatic.com/sites/28ecd9_7b52c92f21e86e2c4701f5ef151d7af1_476.json.z?v=3 was preloaded using link preload but not used within a few seconds from the window’s load event. Please make sure it wasn’t preloaded for nothing.
maze:1 The resource https://static.wixstatic.com/sites/28ecd9_3879b7535d14aa2141350a41c244f702_380.json.z?v=3 was preloaded using link preload but not used within a few seconds from the window’s load event. Please make sure it wasn’t preloaded for nothing.
workerLogger.js:53 Loading the code for the site. To debug this code, open masterPage.js in Developer Tools.
workerLogger.js:53 Loading the code for the My Readocity page. To debug this code, open xb1li.js in Developer Tools.
workerLogger.js:53 IN ON READY. HERE IS WHAT I GOT
workerLogger.js:53 undefined

I assume you are doing import {session} from ‘wix-storage’; ?

You need to put all the stuff that is dependent on the results of the query, inside the .then( )

i.e. put
let value = results.items[0].value;
console.log(“IN ON READY. HERE IS WHAT I GOT”)
console.log(value);

inside the then.

Alternatively you can check out aysnc and await , which is far superior to .then( ) stuff, for mine.

Wix documentation being as hard to find as it is, though, the basic idea is:

in your onReady, change it to

onReady( async function( … etc

And when you do asynchronous code like queries, change it to

var results = await wixData.query(“User”).eq(“_id”, userId)
.find();

/* use the results here */

No more messy “thens”, you can treat the code in a normal (synchronous) manner.

Thank you Mike. The fix was much simpler though. It seems like I was calling the items collection incorrectly. Instead of
let value = results.items[0].value;
I corrected the actual value of the field and it worked
results.items[0].usertype

Well. that’s good that you “fixed it”, but you should still do what I recommended above, or you will get unpredictable results. It may seem fine, but sometimes it will give errors.

will do, thanks Mike

Hi Mike, just want to let you know that your insight on async and await saved my day. The WIX documentation is not great and I wish I had a way to let the world know this amazing function exists so they are not going crazy with their Wix collections.

You’re welcome Vidya, happy to help.

The next time I have a Wix question I going straight to you :slight_smile:

Please guys, i have a similar issue.

I tryed the follow code, but wasnt able to return the value of emailCP field, and with sure, for the tested _owner the database has a emailCP value.

$w.onReady(function () {
let user = wixUsers.currentUser;
userId = user.id;
user.getEmail()
.then((email) => {
userEmail = email;
$w(‘#textTest’).text = userEmail;
wixData.query(“ClienteParceiro”)
.eq(“_owner”, userId)
.find()
.then((results) => {
let item = results.items[0];
let emailCP = item.emailCp;
$w(‘#textTest3’).text = emailCP;
})
.catch((err) => {
let errorMsg = err;
});
$w(‘#textTest2’).text = userId;
console.log(userEmail);
console.log(userId);
});

About the async tip, i try the follow code, but wif sure, i did wrong.

async function getUserData(){
userId = await wixUsers.currentUser.id;
userEmail = await wixUsers.currentUser.getEmail();
console.log(userId, userEmail); }

Hi Daniel,
If userEmail is the one returned as “undefined” you should try the async in your main function call

$w.onReady(async function () {
let user = wixUsers.currentUser;
userId = user.id ;
await user.getEmail()

Hi Vidya, thanks by the reply!

I found my mistake… was at the database permissions. Always is a detail that take several hours of our time… But, im glad that is work now.

I liked the async function… leves the code clean, and i used that.