Reputation: 3949
I am trying to add new users to firestore with the same uid, when they are creatd with createUserWithEmailAndPassword. however I can add users to my user collection, but the id its given is not the same id as the uid. this is how I do it:
const auth = getAuth(db);
const app = getFirestore();
const handleSubmit = useCallback(
async (event) => {
event.preventDefault();
const { email, password, fname, lname } = event.target.elements;
// console.log("clicked", email.value, password.value);
const auth = getAuth(db);
const app = getFirestore();
createUserWithEmailAndPassword(auth, email.value, password.value)
.then(async (userCredential) => {
// Signed in
const user = userCredential.user;
try {
const docRef = await addDoc(collection(app, "users"), {
firstName: fname.value,
lastName: lname.value,
email: email.value,
age: 0,
bday: "",
});
console.log("Document written with ID: ", docRef.id);
} catch (e) {
console.error("Error adding document: ", e);
}
//=================
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
});
},
[history]
);
the ref id it a different id than my uid. what do I have to do to make it save the user with the same id.
also I have tried this
app.collection("users")
doc(user.uid)
.set({...})
but this generates an error!
Upvotes: 1
Views: 1027
Reputation: 598916
If you check the Web version 9 (modular) code sample in the documentation on setting a document, you'll see that setting the document goes like this:
import { doc, setDoc } from "firebase/firestore";
// Add a new document in collection "cities"
await setDoc(doc(db, "cities", "LA"), {
name: "Los Angeles",
state: "CA",
country: "USA"
});
So in your scenario, that'd be:
const docRef = doc(app, "users", user.uid)
await setDoc(docRef, {
firstName: fname.value,
lastName: lname.value,
email: email.value,
age: 0,
bday: "",
});
Upvotes: 3