我需要在Firebase中使用此架构从文档中获取值:
COLLECTION => DOCUMENT => COLLECTION => DOCUMENT
userPolls => userId => dailyPolls => 20200825 => pollDate: "2020/08/25"
status: "Under PUM"
statusCode: "pum"
uid: "zwQnrrBdNCemWyXEW2LHmw8LejA2"
这是我的尝试。但我认为我在弄错时弄错了
final CollectionReference userPollCollection =
Firestore.instance.collection('userPolls');
Future getPoll() async {
final DateTime now = DateTime.now();
final DateFormat formatter = DateFormat('yyyy/MM/dd');
final String formatted = formatter.format(now);
var pollDate = formatted;
var docRef = await applicationUser
.document(userId)
.collection('dailyPolls')
.document(pollDate);
docRef.get().then((onValue) => {print(onValue.data['status'])});
}
我知道这是不对的。你能告诉我如何吗?谢谢。
编辑 作为参考,这是我将数据添加到Firestore数据库的方式:
Future setPoll(UserPoll userPoll) async {
var dt = userPoll.pollDate.replaceAll('/', '');
return await userPollCollection
.document(userId)
.collection('daillyPolls')
.document(dt)
.setData({
'uid': userId,
'pollDate': userPoll.pollDate,
'status': userPoll.status,
'statusCode': userPoll.statusCode
});
}
这就是我尝试获取的方式
Future getPoll() async {
final DateTime now = DateTime.now();
final DateFormat formatter = DateFormat('yyyy/MM/dd');
final String formatted = formatter.format(now);
var pollDate = formatted;
var dt = pollDate.replaceAll('/', '');
var docRef = userPollCollection
.document(userId)
.collection('dailyPolls')
.document(dt);
docRef.get().then((onValue) {
print(onValue.data);
});
}
}
如果我在Peter Haddad的帮助下使用此代码,则在打印result.data
时会得到空值
答案 0 :(得分:1)
您必须执行以下操作:
var docRef = Firestore.instance.collection("userPolls").document(userId).collection('dailyPolls').where("pollDate", isEqualTo: pollDate);
var result = await docRef.getDocuments();
result.documents.forEach((result) {
print(result.data);
});
});
由于pollDate
是文档中的属性,因此您可以使用where()
方法来查询和获取文档