检查文档是否存在,如果不存在,创建并添加数据Firebase



如上所述,我需要创建一个返回"true"如果文件存在,则"false"。如果文档不存在,则需要在函数结束前创建。

当我运行它时,我有这个异常:

Unhandled Exception: 'package:cloud_firestore/src/firestore.dart': Failed assertion: line 129 pos 12: 
'isValidDocumentPath(documentPath)': a document path must point to a valid document.

很容易理解,我没有检查路径是否存在之前获得集合,但我不知道如何处理它。

这是代码:

Future<bool> checkMissingId(String id) async {
String str = id.toLowerCase();
String letter = str[0];
final snapShot =
await FirebaseFirestore.instance.collection(letter).doc(str).get();
if (snapShot == null || !snapShot.exists) {
//if not exists then create it
final _service = FirestoreService.instance;
_service.setData(
path: letter + str,
data: {'id': id},
);
return true;
} else // it already exists, return false
return false;
}

编辑:新代码,但仍然不能工作:

Future<bool> checkMissingId(String id) async {
String str = id.toLowerCase();
String letter = str[0];
String path = letter + "/" + str;
print(path);
try {
final snapShot =
await FirebaseFirestore.instance.collection(path).doc(str).get();
if (snapShot == null || !snapShot.exists) {
return true;
} else
return false;
} catch (e) {
print(e);
return false;
}
}
Future<bool> setId(String id) async {
String str = id.toLowerCase();
String letter = str[0];
String path = letter + "/" + str;
final _service = FirestoreService.instance;
try {
final snapShot =
await FirebaseFirestore.instance.collection(path).doc(str).get();
if (snapShot == null || !snapShot.exists) {
_service.setData(
path: path,
data: {'id': id},
);
return true;
} else
return false;
} catch (e) {
//print(e);
_service.setData(
path: path,
data: {'id': id},
);
return true;
}
}

假设id = "PaninoAvvelenato":我想检查路径"p/paninoavvelenato"上是否存在文档,如果不存在,我需要创建它。

不使用FirestoreService。

Future<bool> setId(String id) async {
String str = id.toLowerCase();
String letter = str[0];
try {
final snapShot = await FirebaseFirestore.instance.collection(letter).doc(str).get();
if (snapShot.exists) {
return false;
} else {
await FirebaseFirestore.instance.collection(letter).doc(str).set({'id': id});
return true;
}
} catch (e) {
// TODO: Do something clever.
return true;
}
}

看起来document for path str不存在,FirebaseFirestore.instance.collection(letter).doc(str).get();抛出异常

所以最好把代码放在

里面
try { 
// code that might throw an exception 
FirebaseFirestore.instance.collection(letter).doc(str).get();
}  
on Exception1 { 
// code for handling exception 
}  
catch Exception2 { 
// code for handling exception 
}