【问题标题】:Querying a specific document from subcollection using firestore and flutter使用firestore和flutter从子集合中查询特定文档
【发布时间】:2020-03-08 20:58:56
【问题描述】:

我想要做的是使用“文档 ID”查询特定文档。但是查询为空。这是我的代码。

 void getEquipDetail() async {
    await _firestore
        .collection('users')
        .document(_userUid)
        .collection('equipment')
        .document(documentID)
        .get()
        .then((DocumentSnapshot ds) {
      equipName = ds.data['equip_name'];
      print(equipName);
    });
  }

当我将“设备”作为根级集合时,这可以正常工作,但由于将其设置为“用户”的子集合,我无法查询特定文档。

这是当前的数据库结构 -collection(用户)* 根级别 -文档(用户标识) - 收藏(设备) -document(设备文件)*这是我试图查询的内容

这是返回的错误

[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: []("equip_name")
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      _EquipmentDetailScreenState.getEquipDetail.<anonymous closure> (package:simmanager/screens/equip_detail_screen.dart:52:26)
#2      _rootRunUnary (dart:async/zone.dart:1132:38)
#3      _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#4      _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
#5      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
#6      Future._propagateToListeners (dart:async/future_impl.dart:707:32)
#7      Future._completeWithValue (dart:async/future_impl.dart:522:5)
#8      _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:30:15)
#9      _completeOnAsyncReturn (dart:async-patch/async_patch.dart:288:13)
#10     DocumentReference.get (package:cloud_firestore/src/document_reference.da<…>

这是可以正常工作的代码(它用于物品而不是设备)

void getItemDetail() async {
    await Firestore.instance
        .collection('items')
        .document(widget.item.document)
        .get()
        .then((DocumentSnapshot snapshot) {
      itemDetails = snapshot.data;
      itemName = snapshot['item_name'];
      itemNum = snapshot['item_num'.toString()];
      itemDesc = snapshot['item_desc'];
      itemLoc = snapshot['item_location'];
      itemQty = snapshot['item_qty'.toString()];
      itemUom = snapshot['item_uom'];
      itemMfr = snapshot['item_mfr'];
      itemStock = snapshot['out_of_stock'];
      lastEditDate = snapshot['edit_date'];
      createDate = snapshot['create_date'];
      imageURL = snapshot['image_url'];

【问题讨论】:

  • 有什么问题?究竟是什么不按您期望的方式工作?您的代码似乎没有检查文档是否确实存在。也许没有。
  • 问题是这返回了一个空值。我已验证文档存在(我在运行此功能之前检查并打印用户 ID 和文档 ID。我仅在查询嵌套在 2 个集合下的文档时遇到此问题。
  • 返回 null 到底是什么?请具体说明您正在观察的内容。还请分享您所做的任何观察都不会“返回 null”的代码。

标签: flutter google-cloud-firestore


【解决方案1】:

您在第一个示例中的代码与第二个示例中的代码并不真正匹配。请仔细比较它们。对于第一个示例,您的意思似乎是:

equipName = ds['equip_name'];

【讨论】:

  • 抱歉,我保留了 .data。无论 .data 是否存在,它仍然返回相同的错误。
  • 从子集合中获取文档与从顶级集合中获取文档没有什么不同。请调试您的代码,以确保您得到的正是您所期望的。
  • 确定更新。我调试并发现错误,在其他功能完成之前调用快照。谢谢你的帮助
猜你喜欢
  • 2021-04-08
  • 2018-06-19
  • 2021-04-18
  • 2020-12-02
  • 1970-01-01
  • 2021-07-12
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多