![](/img/trans.png)
[英]how to retrieve specific data from Cloud Firestore using flutter and dart?
[英]How to delete data from Firestore with specific parameter flutter?
我正在尝试使用where
参数删除一些数据以指定应该删除哪个数据。
我有这个方法,而且效果很好。
final FirebaseFirestore _db = FirebaseFirestore.instance;
Future deleteInstructorDocumentInFirestore(String url) async {
_db.collection(instructorsDocument)
.where("photo", isEqualTo: url)
.get()
.then((value) {
for (var element in value.docs) {
_db.collection(instructorsDocument)
.doc(element.id)
.delete();
}
});
}
所以我用这个尝试了同样的事情,但它不起作用。
火库
Function
final FirebaseFirestore _db = FirebaseFirestore.instance;
Future deleteEvent(String uid, DateTime from, DateTime to) async {
print("From: $from");
print("From type: ${from.runtimeType}");
print("To: $to");
print("To type: ${to.runtimeType}");
_db.collection(instructorsEvent)
.where("uid", isEqualTo: uid)
.where("from", isEqualTo: from)
.where("to", isEqualTo: to)
.get()
.then((value) {
for (var element in value.docs) {
_db.collection(instructorsEvent)
.doc(element.id)
.delete();
}
});
}
我究竟做错了什么。
提前致谢
from
和to
字段是字符串。 但是您试图将它们与不是字符串的 dart DateTime object 进行比较。 因此,它们在任何查询中都不会匹配 - 您的查询根本不返回任何文档,因此没有什么可删除的。 (我建议添加一些调试日志以更好地自己观察这一点。)
Firestore 不会为您将 DateTime 对象转换为字符串,也不会尝试猜测如何为您比较它们。 您必须为您尝试比较的文档字段提供类似类型的值。
因此,如果您的文档字段必须保留字符串,那么您应该找到一种方法将 DateTime 对象转换为字符串,然后再将它们交给 Firestore 查询。 或者,您必须找到另一种表示时间点的方式(在 Firestore 中,通常是时间戳类型字段),然后将对象提供给 Firestore 自然理解为与时间戳相当的查询。
也可以看看:
问题解决了
@Doug Stevenson 谢谢
实用程序
static String toDateTimeToStringFromFirestore(DateTime dateTime) {
final date = DateFormat("yyyy-MM-ddTHH:mm:ss.SSS").format(dateTime);
return date;
}
事件视图模型
Future deleteEvent(String uid, DateTime from, DateTime to) async {
final fromString = Utils.toDateTimeToStringFromFirestore(from);
final toString = Utils.toDateTimeToStringFromFirestore(to);
_db.collection(instructorsEvent)
.where("uid", isEqualTo: uid)
.where("from", isEqualTo: fromString)
.where("to", isEqualTo: toString)
.get()
.then((value) {
for (var element in value.docs) {
_db.collection(instructorsEvent)
.doc(element.id)
.delete();
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.