【发布时间】:2021-02-03 17:22:03
【问题描述】:
如上所述,我需要创建一个函数,如果文档存在则返回“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”上是否存在文档,如果没有,我需要创建它。
【问题讨论】:
-
你作为 str 传入了什么?
-
Str 是一个必须小写的名称。这个想法是“Str”将是集合“letter”中的文档,而“id”将是其中的数据,使用“data: {'id': id}”
-
如果您不知道,您不必检查文档是否存在。如果它不存在 FirebaseFirestore.instance.collection('Test').doc(str).set({'Example': example,}) 将创建一个。如果是这样,它将更新文档中的数据。
-
@Florian 我知道“set”是如何工作的,我的需要是:如果文档已经存在,那么我不需要做任何事情,只需返回 true,但如果它存在,我需要创建它并返回 false。
-
我很好奇你作为 str 传入的内容。问题背后的原因是您是否传递了一些无效字符或无效的文档路径。你提到 str 是一个名字。我希望没有空格...?如果您指定路径,请确保集合以正斜杠结尾。
标签: firebase flutter dart google-cloud-firestore