我正在尝试创建一个系统,人们可以将数据提交到集合中。集合名称和文档名称基于放入其中的变量,有时尚未创建。我想这样做,以便如果集合或文档不存在,那么它们将自动创建。
我以前可以使用它,但由于某种原因,这次它不起作用。
当前不起作用的代码是:
await FirebaseFirestore.instance
.collection('user-content')
.doc('councils')
.collection('council-paydates')
.doc(council)
.collection(year)
.add({"data": "data"});
上面的变量是council和year。
过去用于类似但不同目的的代码如下
await FirebaseFirestore.instance
.collection('reviews')
.doc('councils')
.collection('reviews')
.doc(widget.council)
.collection('councilRatingReviews')
.add({
"POST_DETAILS": {
"UID": userId,
"USERNAME": displayName ?? '',
"DATE_OF_POST": _dateOfPost,
"ANONYMOUS": anonymousComment,
},
"COUNCIL_REVIEW": {
"TITLE": _titleTextController.text.trim(),
"REVIEW": _commentTextController.text.trim(),
"COUNCIL": widget.council,
"OVERALL_RATING": _rating,
},});
用于动态创建上述集合和文档的变量是 widget.council。
任何人都可以帮助我了解如何制作它,以便在当前不存在时创建集合和文档路径。
编辑:输入的年份字符串包含不允许的“/”字符。我刚刚将“/”转换为“-”,它就开始工作了。
解决方案
我试图放入 firebase 路径中的变量“year”中有一个“/”字符,这是不允许的,以下是我如何使其工作的。
String year = "2024/2025"
String convertedYear = year.replaceAll('/', '-');//2024-2025
await FirebaseFirestore.instance
.collection('user-content')
.doc('councils')
.collection('council-paydates')
.doc(council)
.collection(convertedYear)//changed from year to convertedYear
.add({"data": "data"});
将答案发布为社区维基,以便其他面临类似问题的人更容易找到解决方案。
@Ankere 如果我遗漏了什么,请随时添加
文档名称不应包含像
/
这样的转义字符。这可能会导致此类问题。因此,在使用日期作为文档名称时,请将 slash(/)
替换为 hyphen(-)
。
String year = "2024/2025"
String convertedYear = year.replaceAll('/', '-');//2024-2025
await FirebaseFirestore.instance
.collection('user-content')
.doc('councils')
.collection('council-paydates')
.doc(council)
.collection(convertedYear)//changed from year to convertedYear
.add({"data": "data"});
在 firestore
的命名约定中遵循这些
最佳实践。