Discord.js | Displaying a username from an ID returns undefined

I’m currently changing my server’s leaderboard command to display on a Canvas, rather than an embed. A problem I ran into is that since it’s not an embed, grabbing the user’s IDs then displaying their usernames with <@userid> no longer works, the code just returns the ids as plain text. I’m looking for a solution to fix this. Here is the code I have right now:

for (var i in money) {
    let user = client.users.cache.get(`${money[i].ID.slice(25)}`);

    finalLb += `${money.indexOf(money[i])+1} ${user} `${money[i].data} credits`n`;

Result of code

enter image description here

When I console log the user variable, I get all their info, including the username.

enter image description here

I tried user.username, but get the error Cannot read property 'username' of undefined. I am a bit stuck at this point, any help’s appreciated. Thank you!


user.username does work if user is defined. By checking your first image, you can see that the ninth user is undefined there too. As the user is undefined, you can’t get the username property.

Are you sure the ID you get from ${money[i].ID.slice(25)} is correct? If it is, maybe try to fetch the users instead:

for (var i in money) {
  let user = await client.users.fetch(`${money[i].ID.slice(25)}`).catch(console.error);

  finalLb += `${money.indexOf(money[i]) + 1} ${user.username} `${
  } credits`n`;