[英]How to move existing collection/data in Firestore to subcollection?
在我的 firestore 数据库中,我有以下 db 模式填充了文档
root
|
|---transactions/...
我想将所有交易移动到一个新的子集合,如:
root
|
|---users/user/transactions/...
我该如何实现?
在尝试了几种方法之后(见下文),这对我有用:
1. 使用@angular/fire SDK 使用自定义函数迁移数据:
// firebase.service.ts
import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { first, map } from 'rxjs/operators';
@Injectable({
providedIn: 'root',
})
export class FirebaseService {
fromCollection = '<name-of-collection>';
toCollection = '<other-root-level-collection>/<document-id>/<subcollection>';
constructor(private firestore: AngularFirestore) {}
migrateTransactions() {
this.getAllDocuments<YourType>(this.fromCollection).subscribe((documents) => {
documents.forEach(async (document) => {
await this.createDocument(this.toCollection, document);
});
});
}
getAllDocuments<T>(path: string) {
return this.firestore
.collection(path)
.get()
.pipe(
first(),
map((collection) => collection.docs.map((doc) => doc.data() as T))
);
}
createDocument(path: string, document: unknown) {
return this.firestore.collection(path).add(document);
}
}
注意:这只会将所有文档从源添加到目标集合 - 它不会删除原始文档或覆盖任何现有文档,因此使用起来非常安全。 之后,您可以在 Firebase 控制台中删除源集合。
请记住,您可以连接嵌套的集合和文档,并将其作为参数传递给AngularFirestore.collection(path)
(如属性toCollection
)。 这使得遍历嵌套集合变得容易。 我不知道这在其他 SDK 中是否可行。
2. 使用Jeff Delaney 的firestore-migrator 迁移:
这对我不起作用,因为库无法转换 firebase 的时间戳。 如果您的架构中没有任何复杂的数据类型,它可能会起作用。 该库本身是一个很好的实用程序,如果您愿意稍加修改,可以使其在本地工作。
3. 使用Cloud Firestore 托管导出和导入服务进行迁移:
这仅适用于整个数据库或根级别集合的完整备份。 所以这可能不是你要找的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.