如何在 Firebase Firestore 中推送数组值

Le *_*Moi 5 javascript firebase google-cloud-firestore

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

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

我认为合并真不会破坏已经存在的数据?与 firestore api 文档有点挣扎。

这是我的数据结构:

households
  2435djgnfk 
    users [ 
      0: user1 
      1: user2 
    ]
Run Code Online (Sandbox Code Playgroud)

谢谢!

Utk*_*rsh 4

为此,您应该使用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);
Run Code Online (Sandbox Code Playgroud)

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

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