Home > Net >  how to add an object to a document in firebase
how to add an object to a document in firebase

Time:04-09

In my code, I get an object from an existing Firebase collection and then I want to add it to another document as an object, however I don't understand how to do it

  // Create a query against the collection.
const q = query(subjectRef, where("Subject", "==", subject), where("Board", "==", examBoard), where("Level", "==", level));
onSnapshot(q, (snapshot) => {
  snapshot.docs.forEach(doc => {
    //add a document to a subcollection in the collection users
    const auth = getAuth();
    //editted so onAuthState function is not called
    const uid = auth.currentUser.uid
    const docRef = doc(db, "users", uid);
    const colRef = collection(docRef, "subjects");
    addDoc(colRef, {
      //?????
    });
  })

the doc would be added to the collection subjects, this is what the doc looks like: collection subject > document and the structure of the users is (collection) users > (document) user > (collection) subjects > (document) what i want to add

CodePudding user response:

You can get the user ID from auth.currentUser.uid property. Here's how you would achieve this:

const q = query(subjectRef, where("Subject", "==", subject), where("Board", "==", examBoard), where("Level", "==", level));
onSnapshot(q, (snapshot) => {
  snapshot.docs.forEach(doc => {
    //add a document to a subcollection in the collection users
    const auth = getAuth();
    var q = doc.data()
    const colRef = collection(db, "users", auth.currentUser.uid,"subjects");
    addDoc(colRef, {
      Board:q.Board
      Level:q.Level
      Subject:q.Subject
    });
    });
  • Related