简体   繁体   English

"Firestore 更新集合中的所有文档"

[英]Firestore update all documents in collections

I have a firestore collections named users, each users have a generated id with a field score :我有一个名为 users 的 firestore 集合,每个用户都有一个带有字段 score 的生成 id:

users 
    0e8X3VFL56rHBxxgkYOW
        score : 4
    3SeDjrgAWMmh3ranh2u
        score : 5

You can get all the documents in the collection, get their id's and perform updates using those id's:您可以获取集合中的所有文档,获取它们的 id 并使用这些 id 执行更新:

db.collection("cities").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        doc.ref.update({
            capital: true
        });
    });
});

For some strange reason the accepted answer ( thehamzarocks ) wasn't working for me, none of the documents were updated.由于某种奇怪的原因,接受的答案( thehamzarocks )对我不起作用,没有任何文件被更新。 Maybe there's a bug in AngularFire2.也许 AngularFire2 中存在错误。 Anyway, I decided to loop over the docs array of the QuerySnapshot instead of using its forEach method, and add each update to a batch queue.无论如何,我决定遍历 QuerySnapshot 的 docs 数组而不是使用它的 forEach 方法,并将每个更新添加到批处理队列中。 Batching bulk operations is also more efficient than sending a new update request for each update operation.批处理批量操作也比为每个更新操作发送一个新的更新请求更有效。

resetScore(): Promise<void> {
  return this.usersCollectionRef.ref.get().then(resp => {
    console.log(resp.docs)
    let batch = this.afs.firestore.batch();

    resp.docs.forEach(userDocRef => {
      batch.update(userDocRef.ref, {'score': 0, 'leadsWithSalesWin': 0, 'leadsReported': 0});
    })
    batch.commit().catch(err => console.error(err));
  }).catch(error => console.error(error))
}

Batch updates are nice but bare in mind that they are limited to 500 document updates per transaction.批量更新很好,但请记住,每个事务最多只能更新 500 个文档。 If this reset isn't done often maybe simplest approach is:如果不经常进行此重置,最简单的方法可能是:

async function resetScores() {
  const collection = await db
    .collection("users")
    .get()
  collection.forEach(doc=> {
    doc.ref
      .update({
        score: 0
      })
  })
}

Firestore doesn't have the ability to bulk update documents without knowing their IDs. Firestore 无法在不知道文档 ID 的情况下批量更新文档。 You will have to somehow know the document ID of each document to update (perform a query, or do batches of queries), and update each one individually.您必须以某种方式知道要更新的每个文档的文档 ID(执行查询或批量查询),并单独更新每个文档。

I came across this post while searching for similar solutions.我在寻找类似解决方案时遇到了这篇文章。 Firestore now has batched writes , which will update all documents in one go. Firestore 现在具有批量写入功能,可以一次性更新所有文档。 This could be an ideal solution for fewer documents.对于较少的文档,这可能是一个理想的解决方案。

Updating @thehamzarocks's answer:更新@thehamzarocks 的回答:

const batch = db.batch()

db.collection('cities').get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
        const docRef = db.collection('cities').doc(doc.id)
        batch.update(docRef, { capital: true })
    });

    batch.commit();
});

Sorry if the question is old but I thought providing a new answer to this question might be useful to someone else too.对不起,如果问题很旧,但我认为为这个问题提供新答案可能对其他人也有用。 I managed to bulk update the entries of a list using the following command:我设法使用以下命令批量更新列表的条目:

 this.db
  .list<User[]>('users')
  .set('/', users);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM