You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase中使用.where()结合.update()更新数组的问题求助

Fixing the Firestore Array Update Issue with .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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 11:44:10