Home > Net >  Trying to runTransaction through all queried documents but getting FirebaseError: Provided document
Trying to runTransaction through all queried documents but getting FirebaseError: Provided document

Time:10-29

I'm trying to update users' name for all their posts when the user changes their displayName.

I'm trying the answer given in my previous question but running into a firebase reference error. I have tried using the doc.ref.path from the query in transaction.get(docRefPath) & transaction.update(docRefPath, "data") but this has not worked. I'm a little stuck as to what it may be. Am I approaching this the wrong way?

Code:

// cloud function
exports.changeName = functions.region('europe-west2').https.onCall((data, context) => {
  const userName = data.userName;
  const uid = context.auth.uid;
  return `${userName}`;
});


// client side action get all the post documents from collection with users ID
const q = query(collection(db, "Posts"), where("userID", "==", uid));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
    console.log(`documentReference path  = ${doc.ref.path}`);
    const docRefPath = doc.ref.path;
    // update users name on all their posts
    const changedName = httpsCallable(functions, 'changeName');
    changedName({ 
        // our data object
        userName: username 
    }).then((result) => {
        // update document with data
        try {
            runTransaction(db, async (transaction) => {
                const postDoc = await transaction.get(docRefPath);
                if (!postDoc.exists()) {
                    throw "Document does not exist!"
                }
                transaction.update(docRefPath, { userName: result.data });
            });
            console.log("Transaction successfully committed!");
        } catch (e) {
            console.log("transtaction failed: ", e)
        }
        console.log(doc.id, " => ", doc.data());
    }).catch((err) => {
        console.error(err.message);
    })
});

CodePudding user response:

The transaction.get() takes a DocumentReference as a parameter and not the path. Try passing doc.ref instead:

const postDoc = await transaction.get(doc.ref); // <-- not doc.ref.path
  • Related