Firebase中使用.where()结合.update()更新数组的问题求助
.where() Queries Hey there! I see exactly where you're stuck here. The problem with your current code is that doc.data() returns a plain JavaScript object of your document's data—not the actual Firestore document reference that has the update() method. That’s why you’re getting the ".update() is not a function" error.
The Correct Approach
When you get a QuerySnapshot from a .where() query, each item in the snapshot is a DocumentSnapshot. To update the underlying document, you need to access its reference via doc.ref (this is the equivalent of the washingtonRef in the official docs example), then call update() on that reference.
Here's your revised code that should work as expected:
db.collection('users').where('user_id', '==', this.userInfo.user_id) .get() .then(function(querySnapshot) { querySnapshot.forEach(function(doc) { // Use doc.ref to get the document reference, then trigger the update doc.ref.update({ postedProjects: firebase.firestore.FieldValue.arrayUnion("new project") }); }); }) .catch(function(error) { console.error("Error updating document: ", error); });
Bonus Tip: Optimize for Unique Matches
Since you’re querying by user_id (which I assume is unique per user), you don’t need to loop through all results with forEach. You can directly access the first (and only) document in the snapshot to make the code cleaner and more efficient:
db.collection('users').where('user_id', '==', this.userInfo.user_id) .get() .then(function(querySnapshot) { if (!querySnapshot.empty) { const userDoc = querySnapshot.docs[0]; userDoc.ref.update({ postedProjects: firebase.firestore.FieldValue.arrayUnion("new project") }); } else { console.log("No matching user document found"); } }) .catch(function(error) { console.error("Error updating document: ", error); });
Quick Reminder
FieldValue.arrayUnion() will atomically add the value to the array only if it doesn’t already exist—this is perfect for avoiding duplicates in your postedProjects list without writing extra check logic.
内容的提问来源于stack exchange,提问作者KJParker

