繁体   English   中英

Flutter Firebase 中如何在文档字段中保存文档id

[英]How to save the document id in document field while creating it in Flutter Firebase

我正在尝试将文档 ID 保存在新字段中,但如果我使用

'postId': _firebase.collection('Posts').doc().id,

这将生成一个新的 id

有什么建议么

 try {
                    _firebase.collection('Posts').add({
                      'content': _postContent.toString(),
                      'poster': logedInUser.uid,
                      'sentOn': FieldValue.serverTimestamp(),
                      'numOfComments': numberOfComments,
                      'votesNumber': numberOfVotes,
                      'duration': _defaultPostTime,
                      'phoneNumber': logedInUser.phoneNumber,
                      'postId': _firebase.collection('Posts').doc().id,
                    });
}

在此处输入图像描述

      String id = _firebase.collection('Posts').doc().id;
       try {
                    _firebase.collection('Posts').doc(id).set({ 
                      'content': _postContent.toString(),
                      'poster': logedInUser.uid,
                      'sentOn': FieldValue.serverTimestamp(),
                      'numOfComments': numberOfComments,
                      'votesNumber': numberOfVotes,
                      'duration': _defaultPostTime,
                      'phoneNumber': logedInUser.phoneNumber,
                      'postId': id,
                    });
       }

@MotasemX 您可以尝试此方法,也可以先使用日期和时间或任何其他方法生成唯一的 ID 然后将唯一 ID 作为文档 ID以及您的postId

String id = DateTime.now().microsecondsSinceEpoch.toString();
try {
                    _firebase.collection('Posts').doc(id).set({ 
                      'content': _postContent.toString(),
                      'poster': logedInUser.uid,
                      'sentOn': FieldValue.serverTimestamp(),
                      'numOfComments': numberOfComments,
                      'votesNumber': numberOfVotes,
                      'duration': _defaultPostTime,
                      'phoneNumber': logedInUser.phoneNumber,
                      'postId': id,
                    });
       }

暂无
暂无

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

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