This code creates a new document every time the user logs in but my task is to update existing same user ID document if it exists else create a new one. How can I do that in V9 Firebase?
Current Code
setDoc(
query(collectionRef),
// db.collection('users').doc(user.uid).set(
{
email: user.email,
lastSeen: serverTimestamp(),
photoURL: user.photoURL
}, {
merge: true
}
);
Old Code that access document UID:
The first parameter in setDoc() should be DocumentReference:
import { doc, setDoc } from "firebase/firestore"
const docRef = doc(db, "users", user.uid);
setDoc(docRef, {
email: user.email,
lastSeen: serverTimestamp(),
photoURL: user.photoURL
}, {
merge: true
}).then(() => console.log("Document updated"));
Alternatively, You can also use updateDoc().
import {
doc,
updateDoc
} from "firebase/firestore"
update(doc(db, "users", user.uid, {
email: user.email,
lastSeen: serverTimestamp(),
photoURL: user.photoURL
}).then(() => console.log("Document updated"));
Related
try {
const res = await getDoc(doc(db, "chats", combinedId));
if (!res.exists()) {
//create a chat in chats collection
await setDoc(doc(db, "chats", combinedId), { messages: [] });
//create user chats
await updateDoc(doc(db, "userChats", currentUser.uid), {
[combinedId + ".userInfo"]: {
uid: user.uid,
displayName: user.displayName,
photoURL: user.photoURL,
},
[combinedId + ".date"]: serverTimestamp(),
});
await updateDoc(doc(db, "userChats", user.uid), {
[combinedId + ".userInfo"]: {
uid: currentUser.uid,
displayName: currentUser.displayName,
photoURL: currentUser.photoURL,
},
[combinedId + ".date"]: serverTimestamp(),
});
}
} }
I tried to make collections userChats and chats for compound queries but nothing apear except users from registration
I have tried change the rule ,but still no collections sit in firebase except user, my rule in firebase is
enter image description here
firebase collections is enter image description here
I keep getting the error above when trying to sign in with Google on Firebase. My code
const provider = new GoogleAuthProvider();
export const auth = getAuth();
export async function signUpGoogle(userType) {
return await signInWithPopup(auth, provider)
.then((result) => {
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
// ...
// create user in firestore
//init services
// Add a new document in collection "users"
setDoc(collection(db, "users", "/", `${userType}`, '/', 'users'), {
userId: user.uid,
firstName: user.displayName,
lastName: user.displayName,
contactNumber: user.phoneNumber,
county: "",
idNumber: "",
city: "",
zipCode: "",
fullName: "",
email: user.email,
imageAsUrl: {
imageAsUrl: user.photoURL,
},
}).catch((e) => {
console.log(e.toString());
});
sessionStorage.setItem("Auth Token", token);
return true
}).catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
console.log(errorCode, errorMessage);
console.log(error);
// ...
return false
});
}
I have folowed the google documentation about signin with google and javascript
The error that i am getting is
FirebaseError: Expected type 'Zu', but it was: a custom ea object
The setDoc() takes a DocumentReference as a parameter i.e. you must specify the document ID. You can use addDoc() instead if you want to generate a random ID. But it might be useful to use user's UID as the document ID itself so try:
setDoc(doc(db, `users/${userType}/users/${user.uid}`), {
userId: user.uid,
firstName: user.displayName,
// ...
}).catch((e) => {
console.log(e.toString());
});
I'm trying to send data on firebase collection but I can't figure out why it can't be sent. Function called createUserWithEmailAndPassword() works normally. In other functions sending data in firebase collection is working fine when I want to send it, but here it doesn't work for some unknown reason. Is this some bug or what?
My function:
SignUp() {
firebase
.auth()
.createUserWithEmailAndPassword(this.email, this.password);
try {
const unique = this.email;
db.collection("user")
.doc(unique)
.set({
name: this.name,
surname: this.surname,
email: this.email,
birth_date: this.birth_date,
city: this.city,
phone_number: this.phone_number,
});
this.success_register=true;
}
catch(error) {
if ((store.currentUser = null)) this.$router.replace({ name: "signup" });
}
}
db.collection("rooms").doc(channelId).collection("messages").add({
message: input,
timestamp: serverTimestamp(),
user: 'Apollos',
userImage: 'https://naniwallpaper.com/files/wallpapers/eren-yeager/1-EREN%20YEAGER-1080x1920.jpg'
});
How should this be in firestore v9?
import { doc } from "firebase/firestore";
const messageRef = doc(db, "rooms", chanelID, "messages");
const update = {
message: input,
timestamp: serverTimestamp(),
user: 'Apollos',
userImage: 'https://naniwallpaper.com/files/wallpapers/eren-yeager/1-EREN%20YEAGER-1080x1920.jpg'
}
setDoc(messageRef, update, { merge: true });
I'm trying write create user function. I have such code
createUser: function (user) {
return db.User.create({
id: user.id,
username: user.username,
password: sha1(user.password),
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
allow_password: user.allow_password
});
}
but it's correct only when I fill all user's fields. Actually, I strongly need only username and email, but when I put only 2 parameters - I've gotten 500 server error. How I can do other rows implicit?
The answer: you have to convert password before the query
createUser: function (user) {
if(user.password) {
user.password = sha1(user.password);
}
return db.User.create({
id: user.id,
username: user.username,
password: user.password,
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
allow_password: user.allow_password
});
}