假设我有一个文档。我知道它的ID
。现在我想知道该文档中是否存在特定字段。如果没有,我想创建它。可能吗?
PS:我不想使用自己的字段名称并将该值设置为 null
。
最佳答案
How to check whether a particular field exist in a particular firestore document?
要解决这个问题,您可以简单地检查是否无效,如下所示:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
DocumentReference docIdRef = rootRef.collection("yourCollection").document("yourDocumentId");
docIdRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
if (document.get("yourField") != null) {
Log.d(TAG, "your field exist");
} else {
Log.d(TAG, "your field does not exist");
//Create the filed
}
}
}
}
});
要向现有文档添加新的特定字段,请参阅此 post 中的我的答案。
关于java - 如何检查特定 Firestore 文档中是否存在特定字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52860089/