[英]check collection existence - Firestore
例:
在繼續進行事件調度功能之前,我必須先與Firestore約會。
Example in the database:
- Companie1 (Document)
--- name
--- phone
--- Schedules (Collection)
-----Event 1
-----Event 2
我有一個執行新時間表的功能。
根據示例。 我需要檢查Schedules集合是否存在。
如果不存在,則執行調度功能。 如果已經存在,則需要執行其他步驟。
我已經使用了這種模式,而不是正確的。
db.collection("Companies").document(IDCOMPANIE1)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
在進行注冊之前,我需要尋求幫助的方法。
實現此只需檢查無效性即可:
DocumentSnapshot document = task.getResult();
if (document != null) {
Log.d(TAG, "DocumentSnapshot data: " + task.getResult().getData());
//Do the registration
} else {
Log.d(TAG, "No such document");
}
此Task
的結果是DocumentSnapshot
。 基礎文檔是否實際存在可以通過exist()方法獲得。
如果文檔確實存在,則可以調用getData獲取文檔的內容。
db.collection("Companies").document(IDCOMPANIE1)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
if(document.exists()) {
//Do something
} else {
//Do something else
}
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
如果您想知道task
是否為空,請使用以下代碼行:
boolean isEmpty = task.getResult().isEmpty();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.