在.where(而不是.doc)中使用firebase .update [英] Using firebase .update within a .where (instead of .doc)

查看:57
本文介绍了在.where(而不是.doc)中使用firebase .update的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Firebase的新手,正在挣扎一点.

I am new to firebase and am struggling a little bit.

当前,我正在尝试更新文档中用户内的数组.但是,我无法使用唯一ID将用户与当前用户匹配,因为每个用户的唯一ID是其用户名,并且自创建以来可能已更改.

Currently, I am trying to update an array within a user, within a document. However, I cannot match the user to current user using the unique ID, as each users unique ID is their username, and it may have changed since creation.

我认为使文档用户与当前用户匹配的最佳方法是使用.where().get(),然后使用"update()"更新数组.

I figured the best way to match the documents user to the current user would be to use a .where().get() and then use an "update()" to update the array.

现在,这就是我被困住的地方.在Firebase文档中,其使用.update的示例附加到.doc

Now, this is where I am getting stuck. In the firebase documents, their example of using .update is attached to a .doc

var washingtonRef = db.collection("cities").doc("DC");

//Atomically add a new region to the "regions" array field.
washingtonRef.update({
  regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")
});

但是,当我使用.where时,我假设我必须使用引用和快照.但是,我不太确定引用在这种情况下如何工作,以及如何正确更新.

However, as I am using a .where, I assume I have to use references and snapshots. But, I am not quite sure how references work in this scenario and, with that, how to update properly.

这是我经过一阵混乱后得到的代码,但是无论我的版本如何,我都无法弄清楚.(本质上,我想将一个新项目(在本例中为"new project"添加到postProjects的用户数组中.)

Here is the code I have after a while of messing round, but no matter my variations i cannot figure it out. (essentially, I want to add a new project (in this case called "new project" to the users array of postedProjects.)

 db.collection('users').where('user_id', '==', this.userInfo.user_id)
  .get()
  .then(function(querySnapshot)  {
    querySnapshot.forEach(function(doc) {

    doc.data().update({
      postedProjects: firebase.firestore.FieldValue.arrayUnion("new project")
    })
  })
})

这给我一个错误".update()不是函数".

This gives me an error of ".update() is not a function".

有人可以帮助我解决我的问题,告诉我 在这种情况下应如何正确使用引用?

Is anyone able to help me with my solution to show me how references should properly be used in this scenario?

推荐答案

您快到了.但是,您无法更新 DocumentSnapshot 的数据,因为那是文档数据的内存表示形式.相反,您需要获取 DocumentReference 并对此调用 update .

You're almost there. You can't update the data of DocumentSnapshot though, since that is the in-memory representation of the document data. Instead you need to get the DocumentReference and call update on that.

doc.ref.update({
  postedProjects: firebase.firestore.FieldValue.arrayUnion("new project")
})

这篇关于在.where(而不是.doc)中使用firebase .update的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆