Firebase Firestore遍历集合并更新文档时出现TypeError: doc.update is not a function错误的求助
Hey there! Let's get this sorted out for you. The error you're seeing—Uncaught (in promise) TypeError: doc.update is not a function—is super common when you're starting out with Firestore writes. Here's why it's happening and how to fix it:
错误原因
When you loop through a querySnapshot, each doc in the loop is a DocumentSnapshot object. This is just a read-only snapshot of the document's current data at the time you fetched the collection—it doesn't have methods like update() because it's not a reference to the actual document in the database.
To update the document, you need to grab its DocumentReference instead, which is accessible via the ref property of the snapshot.
基础修正代码
Here's your code adjusted to use the document reference for updates:
const db = firebase.firestore(); db.collection("users_highscores").get().then(function(querySnapshot) { querySnapshot.forEach(function(docSnapshot) { // 获取指向该文档的引用 const docRef = docSnapshot.ref; // 调用引用上的update方法来修改文档 docRef.update({ highscores_daily: {} }) .then(() => { console.log(`Successfully updated document: ${docSnapshot.id}`); }) .catch((err) => { console.error(`Failed to update document ${docSnapshot.id}:`, err); }); }); });
优化:使用批量写操作
If your collection has a lot of documents, firing individual update requests can be inefficient (and might hit rate limits). Firestore supports batch writes, which let you group up to 500 operations into a single atomic request:
const db = firebase.firestore(); const batch = db.batch(); db.collection("users_highscores").get().then(function(querySnapshot) { querySnapshot.forEach(function(docSnapshot) { const docRef = docSnapshot.ref; // 将更新操作添加到批量任务中 batch.update(docRef, { highscores_daily: {} }); }); // 提交所有批量操作 return batch.commit(); }).then(() => { console.log("All documents updated successfully!"); }).catch((err) => { console.error("Batch update failed:", err); });
额外注意事项
- 处理超过500个文档: If your collection has more than 500 documents, you'll need to split the batch into chunks (e.g., commit every 500 operations) to stay within Firestore's limits.
- 安全规则: Make sure your Firestore security rules allow write access to the
users_highscorescollection—otherwise, you'll get permission denied errors even with correct code. - 原子性: Batch operations are atomic—either all updates succeed, or none do. This is great for maintaining data consistency.
内容的提问来源于stack exchange,提问作者user15794643

