Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

628
Views
How to get all users with a role in Discord.js in a array

I am trying to get all the members with a certain role. For example, there is role of gurdian in my discord server with a id of 872029521484873779. I want a list of all the users Name in a array who have gurdian as a role in my server. My code is as below

let nameList= msg.guild.roles.cache.get('role_id').members.map(m=>m.user.tag);

However, In result it only returns one user in the nameList whereas as there are 9 users with the role assigned to them. What am I doing wrong here which is bringing me only 1 user not the rest of 9 users in a list in array. I am new to discord.js

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Your mistake might be a simple confusion with the id numbers. The number in your code is different then the number in your question

about 4 years ago · Juan Pablo Isaza Report

0

This is happening because the members aren't cached. So you only see 1 person logging because only 1 person is in the cache. To fix this, you can fetch all members by doing msg.guild.members.fetch(), then use msg.guild.roles.cache.get("roleid").members.map(m => m.user.tag) to get the real output. Please do note that you will need the GUILD_MEMBERS intent if you are on v13.

Fetching members from the guild will store them in cache. So when you do do role.members, you get the members who have this role.

If you don't fetch members, then the info won't be accurate. Discord.js stores users in cache. This happens whenever someone sends a message, updates their profile or anything about themselves WHILE the bot is online. So if you restart your bot, no one will be in the cache.

Why is fetch different from cache?

Fetch gets the info directly from discord, while cache is checking if the user is stored locally. When you fetch members, they are automatically stored in the cache as well.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!