如何从Firestore数据库获取自动生成的ID

时间:2020-08-03 01:12:07

标签: flutter dart google-cloud-firestore

我在firestore db中创建了一个数据库,用于将用户的评论存储在帖子中。添加评论后,数据库会自动生成评论ID。现在,我想使用其ID删除评论,以避免同时删除其他评论。我如何获得评论自动生成的ID以便从数据库中删除它?

这是我在数据库中添加注释的代码。

addComments() {
    commentsRef.document(postId).collection('comments').add({
      'username': currentUser.username,
      'comment': commentController.text,
      'avatar': currentUser.photoUrl,
      'timestamp': DateTime.now(),
      'userId': currentUser.id,
      'likes': {},
    });
    bool isNotPostOwner = postOwnerId != currentUser.id;
    if (isNotPostOwner) {
      activityFeedRef.document(postOwnerId).collection('feedItems').add({
        'type': 'comment',
        'commentData': commentController.text,
        'timestamp': DateTime.now(),
        'postId': postId,
        'ownerId': currentUser.id,
        'username': currentUser.username,
        'userProfileImg': currentUser.photoUrl,
        'mediaUrl': postMediaUrl,
      });
    }
    commentController.clear();
  }

我尝试使用此代码将其删除,但它会删除注释集合中的所有数据

  deleteComment() async {
    QuerySnapshot commentsSnapshot = await commentsRef
        .document(postId)
        .collection('comments')
        .getDocuments();
    commentsSnapshot.documents.forEach((doc) {
      if (doc.exists) {
        doc.reference.delete();
      }
    });
  }

2 个答案:

答案 0 :(得分:1)

数据库自动生成评论ID

实际上,这不是真的。客户端SDK会在本地生成随机ID,实际上可以保证不会与其他任何可能存在的ID发生冲突。

如果您的客户端应用程序以后需要使用该文档,则必须:

  1. 记住该ID供以后使用。
  2. 使用字段中的信息查询Firestore以查找文档。

这是您仅有的两个选择。

如果要在调用add()之后获取文档的ID,请注意add()返回一个Future,该Future用新文档的DocumentReference解析。该DocumentReference具有documentID属性。

答案 1 :(得分:0)

您可以在生成文档ID时获得它。

db.collection('students').add({'name': 'John'})
.then((val)=> print(val.documentID)});