Home > Software engineering >  How do I changed this Firebase version 8 syntax to version 9?
How do I changed this Firebase version 8 syntax to version 9?

Time:02-22

This is the syntax I originally used to add a document to a subcollection "posts". But I think it is not supported by firebase version 9

const unsubscribe = db.collection("users").doc(firebase.auth().currentUser.email).collection("posts").add({
  imageUrl: currentLoggedInUser.unsername,
  user: CurrentLoggedInUser.username,
  profile_picture: CurrentLoggedInUser.profilePicture,
  owner_uid: auth.currentUser.uid,
  caption: caption,
  createdAt: serverTimestamp(),
  likes: 0,
  likes_by_users: [],
  comments: [],
}).then(() => navigation.navigate('HomeScreen'))
return unsubscribe

What I tried

const unsubscribe = (doc(collection(db, "users")), auth.currentUser.email, addDoc(collection("posts"), {
  imageUrl: imageUrl,
  user: CurrentLoggedInUser.username,
  profile_picture: CurrentLoggedInUser.profilePicture,
  owner_uid: auth.currentUser.uid,
  caption: caption,
  createdAt: serverTimestamp(),
  likes: 0,
  likes_by_users: [],
  comments: [],
}).then(() => navigation.navigate('HomeScreen'))
return unsubscribe

CodePudding user response:

Things become much more readable if you capture the result of some of these operations in a meaningfully named variable.

const usersRef = collection(db, "users");
const userRef = doc(usersRef, auth.currentUser.email);
const postsRef = collection(userRef, "posts");
const promise = addDoc(postsRef, {
  imageUrl: imageUrl,
  user: CurrentLoggedInUser.username,
  profile_picture: CurrentLoggedInUser.profilePicture,
  owner_uid: auth.currentUser.uid,
  caption: caption,
  createdAt: serverTimestamp(),
  likes: 0,
  likes_by_users: [],
  comments: [],
});
return promise.then(() => navigation.navigate('HomeScreen'));

Once the above works, you can rewrite the first three lines to:

const postsRef = collection(db, "users", auth.currentUser.email, "posts");
  • Related