2 回答

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超6個(gè)贊
每次您撥打電話時(shí)document()
,您都會(huì)獲得一個(gè)新的唯一 ID。因此,請務(wù)必只調(diào)用一次,這樣您就只處理一個(gè) ID。
首先獲取文檔參考:
DocumentReference ref = db.collection("user_details").document();
獲取其ID:
String id = ref.getId();
然后編寫要發(fā)送的數(shù)據(jù):
Map map = new HashMap<>(); map.put("username", username); map.put("email", email); map.put("id", id);
最后,將該數(shù)據(jù)放入前面引用的文檔中:
ref.set(map)...

TA貢獻(xiàn)2011條經(jīng)驗(yàn) 獲得超2個(gè)贊
為了能夠?qū)⒛?ID 保存在文檔中,您首先需要?jiǎng)?chuàng)建一個(gè)文檔。問題是 ID 是在創(chuàng)建文檔的同時(shí)創(chuàng)建的。但我們可以首先創(chuàng)建 ID,然后像這樣發(fā)送我們的文檔:
val matchRef = mFirestore.collection(FirebaseHelp().USERS).document(user.uid).collection(FirebaseHelp().MATCHES).document() //notice this will not create document it will just create reference so we can get our new id from it
val newMatchId = matchRef.id //this is new uniqe id from firebase like "8tmitl09F9rL87ej27Ay"
該文檔尚未創(chuàng)建,我們只是有一個(gè)新的 id,所以現(xiàn)在我們將此 id 添加到 POJO 類中(或者我猜它是 POKO,因?yàn)樗?Kotlin)。
class MatchInfo(
var player1Name: String? = null,
var player2Name: String? = null,
var player3Name: String? = null,
var player4Name: String? = null,
var firebaseId: String? = null, //this is new added string for our New ID
)
現(xiàn)在我們創(chuàng)建要上傳到 firebase 的對(duì)象:
val matchInfo = MatchInfo(player1?.mName, player2?.mName, player3?.mName, player4?.mName, newMatchId)
或者我們在將對(duì)象發(fā)送到 firebase 之前設(shè)置新的 id
matchInfo.firebaseId = newMatchId
現(xiàn)在我們使用新 ID 將對(duì)象發(fā)送到 firebase,如下所示:
val matches = mFirestore.collection(FirebaseHelp().USERS).document(user.uid).collection(FirebaseHelp().MATCHES)
matches.document(newMatchId).set(matchInfo) // this will create new document with name like"8tmitl09F9rL87ej27Ay" and that document will have field "firebaseID" with value "8tmitl09F9rL87ej27Ay"
添加回答
舉報(bào)