如何将用户UID设为Firestore文档ID?遇currentUser为空错误
TypeError: firebase.auth(...).currentUser is null When Using UID as Firestore Document ID Hey there! Let's break down why you're running into this error and how to fix it.
The Root Cause
That null error happens because Firebase Authentication operations are asynchronous, and you're trying to access currentUser before the auth system has finished initializing or processing your registration request. When you call firebase.auth().currentUser right after triggering a sign-up, the user session hasn't been fully created yet—so it returns null.
The Fix: Use the Auth Promise to Get the User Directly
Instead of relying on currentUser right away, use the Promise returned by Firebase's createUserWithEmailAndPassword method. This gives you direct access to the user object as soon as registration succeeds, no waiting for currentUser to update.
Here's how to modify your reg() function:
// Firestore Cloud Database var db = firebase.firestore(); function reg(){ const txtname = document.getElementById('txtuname').value; const txtEmail = document.getElementById('txtemail').value; const txtPass = document.getElementById('txtpass').value; // Step 1: Create the user with email/password (async operation) firebase.auth().createUserWithEmailAndPassword(txtEmail, txtPass) .then((userCredential) => { // Registration succeeded—get the user object directly from the credential const user = userCredential.user; // Step 2: Use the user's UID as the Firestore document ID return db.collection("users").doc(user.uid).set({ name: txtname, email: txtEmail // Add any other user fields you need here }); }) .then(() => { // Success! Let the user know alert("Registration complete!"); // Optional: Redirect to a dashboard or profile page }) .catch((error) => { // Handle errors (e.g., duplicate email, weak password) alert(`Oops, something went wrong: ${error.message}`); console.error("Auth/Firestore error:", error); }); }
Bonus: Handling Persistent Sessions
If you need to access the user's UID on page load (for returning logged-in users), use Firebase's onAuthStateChanged listener. This waits until the auth system has loaded the user's session, so you never get a null value when a user is logged in:
// Run this when your page loads firebase.auth().onAuthStateChanged((user) => { if (user) { // User is signed in—use their UID for Firestore operations console.log("Logged in user UID:", user.uid); // Example: Fetch the user's Firestore document db.collection("users").doc(user.uid).get() .then((doc) => { if (doc.exists) { console.log("User data:", doc.data()); } else { console.log("No user document found—maybe create it here?"); } }); } else { // No user is signed in—show login/register forms console.log("No active user session"); } });
Key Takeaways
- Never rely on
currentUserin synchronous code right after auth actions (sign-up/sign-in)—always use the Promise callback or auth state listener. - The
userCredential.userobject fromcreateUserWithEmailAndPasswordorsignInWithEmailAndPasswordis guaranteed to exist when the Promise resolves, so it's the safest way to get the UID immediately after auth.
内容的提问来源于stack exchange,提问作者JM007

