Mof*_*lam 1 firebase flutter google-cloud-firestore
我们可以在添加数据之前在实时数据库中推送密钥,但在云 Firestore 中我找不到任何方法在添加数据之前找到唯一密钥。
String uniqueKey = ref.push().getKey();
Run Code Online (Sandbox Code Playgroud)
所以我正在执行两个操作添加然后更新。如果我可以在将数据添加到 firestore 之前获得唯一键,我可以执行一个操作,只需添加文档中包含的唯一键即可。
目前我正在这样做。
收藏参考
final sitesRef = FirebaseFirestore.instance
.collection('book_mark')
.doc(getUserId())
.collection("link")
.withConverter<SiteModel>(
fromFirestore: (snapshots, _) => SiteModel.fromJson(snapshots.data()!),
toFirestore: (siteModel, _) => siteModel.toJson(),
);
Run Code Online (Sandbox Code Playgroud)
添加文档,然后从响应中获取文档 ID,然后使用文档 ID 更新文档。因此,如果更新操作因某种原因失败,我将无法再访问该文档。所以这会产生一个问题。
Future<String> addSiteFireStore(SiteModel siteModel) async {
try {
DocumentReference<SiteModel> response = await sitesRef.add(siteModel);
final Map<String, dynamic> data = <String, dynamic>{};
data['docId'] = response.id;
sitesRef.doc(response.id).update(data);
_logger.fine("Link added successfully");
return "Link added successfully";
} on Exception catch (_) {
_logger.shout("Could not add link.Please try again");
return "Could not add link.Please try again";
}
}
Run Code Online (Sandbox Code Playgroud)
有什么办法可以提前获取文档ID吗?提前致谢。
您可以通过调用doc()(不带参数)CollectionReference. 然后,您可以id从新文档引用中获取属性,类似于调用getKey()新 RTDB 引用的方式。
所以:
final newRef = FirebaseFirestore.instance
.collection('book_mark')
.doc();
final newId = newRef.id;
Run Code Online (Sandbox Code Playgroud)
另请参阅 FlutterFire 上的文档CollectionReference.doc()。
| 归档时间: |
|
| 查看次数: |
1992 次 |
| 最近记录: |