【问题标题】:How to push an array value in Firebase Firestore如何在 Firebase Firestore 中推送数组值
【发布时间】:2018-09-29 15:34:23
【问题描述】:

我正在尝试推送一个数组元素,但正在销毁那里的所有内容并替换为推送的数据:

db .collection('households')
  .doc(householdId)
  .set( { users: [uid], }, { merge: true }, )
  .then(() => { resolve(); })
  .catch(() => reject());

我认为合并 true 不会破坏已经存在的数据?使用 firestore api 文档有点吃力。

这是我的数据结构:

households
  2435djgnfk 
    users [ 
      0: user1 
      1: user2 
    ]

谢谢!

【问题讨论】:

  • 你能告诉我你的uid数组吗?

标签: javascript firebase google-cloud-firestore


【解决方案1】:

您应该为此使用Firestore Transaction

const householdRef = db.collection('households').doc(householdId);

const newUid = '1234'; // whatever the uid is...

return db.runTransaction((t) => {
  return t.get(householdRef).then((doc) => {
    // doc doesn't exist; can't update
    if (!doc.exists) return;
    // update the users array after getting it from Firestore.
    const newUserArray = doc.get('users').push(newUid);
    t.set(householdRef, { users: newUserArray }, { merge: true });
  });
}).catch(console.log);

更新数组或存储对象而不首先获取它总是会破坏 firestore 中该数组/对象内的旧值。

这是因为它们是字段而不是实际文档本身。因此,您必须先获取文档,然后再更新值。

【讨论】:

  • 谢谢@Utkarsh 我会试试这个。当我将第一个用户设置为数组时,他们得到的键值为 0。有没有办法增加这个,所以下一个用户是 1、2、3 等等?
  • @LeMoi。在我的代码示例中,我使用了push() 方法,该方法将始终将新用户的 uid 附加到现有数组而不覆盖现有元素。如果您想显式存储每个用户的索引,您可能应该将用户列表保存为对象而不是数组。不过,我真的无法评论这种方法是好是坏。
【解决方案2】:

我认为现在您可以通过 FieldValue.arrayUnion 在文档上使用 update 命令做得更好,而不会破坏同时添加的数据。像这样:

const admin = require('firebase-admin');
let db = admin.firestore();
const FieldValue = admin.firestore.FieldValue;
let collectionRef = db.collection(collection);
let ref = collectionRef.doc(id);

let setWithOptions = ref.update(arrayFieldName, FieldValue.arrayUnion(value));

https://firebase.googleblog.com/2018/08/better-arrays-in-cloud-firestore.html中所述

【讨论】:

    【解决方案3】:

    Firestore 中的数组不是这样工作的。根据documentation

    虽然 Cloud Firestore 可以存储数组,但不支持查询数组成员或更新单个数组元素。

    如果要更改数组中的任何元素,则必须先从文档中读取数组值,在客户端对其进行更改,然后将整个数组写回。

    可能还有其他更适合您的用例的数据建模方法。上面链接的文档页面有一些解决方案。

    【讨论】:

      猜你喜欢
      • 2020-11-11
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 2019-08-09
      相关资源
      最近更新 更多