Firebase多手机号键条目场景下,已登录用户如何获取自身手机号?
Hey Gaurav, let's walk through how to pull your own phone number when logged in, given your database setup where there are multiple entries with phone numbers as keys (similar to Courtney Miller's structure but with multiple rows).
First, the core thing here is: when you're logged in, your system already has a unique identifier for your account (like a user_id, session ID, or data from your auth token). You'll use this ID to link back to the phone number entries tied to your account.
Here are the most common approaches depending on your setup:
1. Direct Database Query (using your user ID)
Since your database has multiple phone number entries, there must be a way to associate each phone number with a specific user. Assuming you have a table (let's say user_phone_associations) where phone_number is the key and user_id is a foreign key linking to your user account:
- Run a query that filters using your logged-in user's ID to get the phone number(s) tied to you. For example, in SQL:
SELECT phone_number FROM user_phone_associations WHERE user_id = 'your_logged_in_user_id'; - If a user can have multiple phone numbers, add a flag like
is_primaryto mark the main one, and adjust the query:SELECT phone_number FROM user_phone_associations WHERE user_id = 'your_logged_in_user_id' AND is_primary = TRUE;
2. Pull from Session/Auth Token
Many systems store frequently used user data (like phone numbers) in the user's session or JWT auth token during login to avoid repeated database calls:
- If you're using server-side sessions, access the phone number directly from the session object. For example, in Python/Django:
request.user.phone_numberor in Node.js/Express:req.session.user.phone_number. - If using JWT, decode the token's payload to extract the phone number field (just make sure this data was included when the token was issued at login).
Key Notes
- Always use your unique user identifier (not the phone number itself) to query—this ensures you get the correct phone number(s) linked to your account, even if there are multiple entries in the database.
- Double-check your database relationships to confirm each phone number entry is properly associated with a user ID; without this link, you won't be able to reliably map the phone number to your account.
内容的提问来源于stack exchange,提问作者Gaurav Atul

