Get data using mapping from struct

web3js

I have a struct –

struct AppData {
    uint256 SrNo;
    uint256 UserID;
    uint256 RefID;
    address Wallet;
}

and Mapping

mapping(uint256 => AppData) public AppUsers;

So I am not mapping on address as there might be same address for different users.
SrNo is normal serial nos. and I add data using SrNo (It's using to add data for array id)
But from frontend I always get UserID and I have to check if this UserID exists and it's a random no. field. So to find it I wrote a code like:
TotalUsers is a field which keeps track of total users.

function GetUserID(uint256 uID) public view returns  (uint256 ) {
    uint256 mVal;
    for (uint256 i = 1;i <= TotalUsers; i++) {
        if (AppUsers[i].UserID == uID) {
            mVal= AppUsers[i].SrNo;        
        }
    }
    return mVal;
}

It working fine but I wonder, if there is any one line code to achieve this or any other shorter way.
If data increases, it would take time each time.

Best Answer

Going through your user IDs one by one like that will eventually get prohibitively slow. You should almost certainly be keying your mapping on UserID if you expect there to be a 1:1 relationship between UserID and AppData. If you expect a 1:many relationship, then you have two options:

  1. Keep a separate mapping of UserIDs to SrNos and use that mapping to find the correct AppData.
  2. Emit an event when you create a new AppData indexed by UserID that you can query to find all relevant AppData structs.
Related Topic