当您在集合中有数百万个文档时,可以'当您的机器时,它会立即获得所有它们。 Firecode' s可配置的遍历器对象让您使用批处理以简单,直观和内存的高效方式执行此操作。
Firecode是一个非常轻的,键入良好的零依赖库,可用于各种场景。您可以在数据库迁移脚本中使用它(例如,当您需要向所有文档添加新字段)或需要定期检查集合中的每个文档的计划云功能或从集合中检索某些数据的本地运行脚本。
Firecode旨在使用Firebase管理SDK,因此如果您已经安装了它,请运行
假设我们想向所有用户发送电子邮件。我们有一个需要遍历的用户集合。以下代码使用Firecode Traverser简单有效地执行此操作。
从&#39导入{fireestore}; firebase-admin' ;导入{createTraverser}从' @ firecode / admin' ; const userscollection = firestore()。集合('用户'); const traverser = creoctetraverser(用户电影,{//我们希望每批都有500个文档。显然,最后批量的大小可能小于500批次:500,//我们希望等待在移动到下一个批量睡眠中的睡眠:真实,//我们' ll等待500ms,然后才能移动到下一个批量擦除折叠的禁区:500,}); const {batchcount,doccount} =等待遍历。遍历(异步(Snapshots)=> {const batchsize =快照。长度; const sendemailtoeachuserinbatch =()=> promise。所有(快照。映射(Snapshots。映射){const {email,firstname} = snapshot。数据();等待SendeMail({to:电子邮件,内容:`hello $ {firstname}!`}); await sendemailtoachuserinbatch();控制台。日志(`在本批处理中成功通过电子邮件发送$ {batchsize}用户。 `);});安慰 。日志(`遍历完成!我们通过$ {batchcount}批次通过电子邮件发送$ {doccount}用户!`);
通过该引用CreateTraverser()函数并使用我们所需的配置创建遍历
调用.Traverse()使用异步回调调用每批文档快照
这几乎总结了这个图书馆的核心功能! .Traverse()方法返回一个解析当整个遍历饰面时的承诺,如果您有数百万的文档可能需要一段时间。承诺用包含遍历细节的对象来解决例如遍历细节。您触摸的文档数量。
const projectScollection = firestore()。集合('项目'); Const Migrator = CreateBatchMigrator(ProjectScollection,{Batchsize:250}); const {migrationddoccount} =等待迁移器。更新(' isCompleted' false);安慰 。日志(`成功更新$ {migrationdoccount}项目!`);
键入userdoc = {firstname:string; LastName:String; }; const userscollection = firestore()。集合('用户')作为firestore。集合reference< UserDoc> ; Const Migrator = CreateBatchMigrator(UsersCollection,{Batchsize:250}); const {migrationddoccount} =等待迁移器。更新((snap)=> {const {firstname,lastname} = snap。data(); return {fullname:`$ {firstname} $ {lastname}`,lastname}`,});安慰 。日志(`成功更新$ {migrationDoccount}用户!`);
键入userpostdoc = {text:string;帖子?:Firestore。时间戳; }; const userpostscollectiongroup = firestore()。 CollectionGroup('帖子')作为fireestore。 CollectionGroup< Userpostdoc> ; Const Migrator = CreateBatchMigrator(UserPostScollectionGroup,{Batchsize:250}); const {migrationddoccount} =等待迁移器。更新((snap)=> {const {postedat} = snap。data(); return {publentedat:postedat!,// safe to sensert postedat:firestore。fieldvalue。delete(),}},(snap)= > snap。data()。postedat!== undefined //如果它没有,它有一个`postedat`领域);安慰 。日志(`成功更新$ {migrationDoccount}用户!`);