【问题标题】:Query with reference in firestore在 Firestore 中使用参考查询
【发布时间】:2021-08-02 06:31:01
【问题描述】:

我正在尝试在 firestore 的集合中查找具有特定参考字段的所有文档。我看过一些关于此的文章,但似乎没有一篇有效。我希望有人能告诉我我做错了什么。这是我尝试的第一个代码sn-p

const childOrgReference = db.collection(`organisations/${context.params.orgId}/childOrganisations`).doc(context.params.childOrgId);
    // Find all people with corresponding childOrgReference
    db.collection(`organisations/${context.params.orgId}/people`).where("childOrgReference", '==', childOrgReference).get()
        .then(function(querySnapshot) {
          querySnapshot.forEach(function(docu) {
            db.collection(`organisations/${context.params.orgId}/people`).doc(docu.id).update({
              "isDeleted": true,
            });
          });
        });

问题是没有找到文档,我通过记录 id 进行了测试。 childOrgReference 应该是正确的。我还尝试了另一段代码:

// const childOrgReference = db.collection(`organisations/${context.params.orgId}/childOrganisations`).doc(context.params.childOrgId);
    // Find all people with corresponding childOrgReference
    db.collection(`organisations/${context.params.orgId}/people`).where("childOrgReference.id", '==', context.params.childOrgId).get()
        .then(function(querySnapshot) {
          querySnapshot.forEach(function(docu) {
            db.collection(`organisations/${context.params.orgId}/people`).doc(docu.id).update({
              "isDeleted": true,
            });
          });
        });

有人知道我做错了什么吗?


编辑: 这是我当前的代码:

const childOrgReference = db.collection(`organisations/${context.params.orgId}/childOrganisations`).doc(context.params.childOrgId);
    logger.log(childOrgReference);

    // Find all people with corresponding childOrgReference
    db.collection(`organisations/${context.params.orgId}/people`)
        .where("childOrgReference", '==', childOrgReference)
        .get()
        .then(function(querySnapshot) {
          const updates = [];
          querySnapshot.forEach(function(docu) {
            logger.log(docu.id);
            const docuRef = db.collection(`organisations/${context.params.orgId}/people`).doc(docu.id);
            updates.push(docuRef.update({"isDeleted": true}));
          });

          Promise.all(updates).then(() => {
            console.log("Documents Updated");
          }).catch((e) => console.log(e));
        });

记录参考日志如下:

DocumentReference {
  _firestore: Firestore {
    _settings: {
      projectId: 'fmis-online-dev',
      firebaseVersion: '9.6.0',
      libName: 'gccl',
      libVersion: '4.9.9 fire/9.6.0',
      ignoreUndefinedProperties: true
    },
    _settingsFrozen: true,
    _serializer: Serializer {
      createReference: [Function],
      createInteger: [Function],
      allowUndefined: true
    },
    _projectId: 'fmis-online-dev',
    registeredListenersCount: 0,
    bulkWritersCount: 0,
    _backoffSettings: { initialDelayMs: 100, maxDelayMs: 60000, backoffFactor: 1.3 },
    _clientPool: ClientPool {
      concurrentOperationLimit: 100,
      maxIdleClients: 1,
      clientFactory: [Function],
      clientDestructor: [Function],
      activeClients: Map {},
      failedClients: Set {},
      terminated: false,
      terminateDeferred: [Deferred]
    }
  },
  _path: ResourcePath {
    segments: [
      'organisations',
      '3dkI69YGRE20AMn9oNGL',
      'childOrganisations',
      'bunEfTrEjtNxaBlpT2zk'
    ]
  },
  _converter: {
    toFirestore: [Function: toFirestore],
    fromFirestore: [Function: fromFirestore]
  }
} 

这是在 Firestore 控制台中显示的参考:

问题是找不到人员文档。 id 没有被记录。我不知道哪里出了问题,但我怀疑人员文档中的引用可能不正确。但是,我不知道它应该是什么。

【问题讨论】:

    标签: node.js firebase google-cloud-firestore


    【解决方案1】:

    您的代码似乎正确并且对我有用。但是,您没有处理承诺。你应该使用承诺链或异步等待:

    const childOrgReference = db.collection(`organisations/${context.params.orgId}/childOrganisations`).doc(context.params.childOrgId);
    
    // Find all people with corresponding childOrgReference
    db.collection(`organisations/${context.params.orgId}/people`)
      .where("childOrgReference", '==', childOrgReference)
      .get()
      .then(function (querySnapshot) {
        const updates = []
        querySnapshot.forEach(function (docu) {
          const docuRef = db.collection(`organisations/${context.params.orgId}/people`).doc(docu.id) 
          updates.push(docuRef.update({"isDeleted": true});
        });
      
        Promise.all(updates).then(() => {
          console.log("Documents Updated")
        }).catch(e => console.log(e))
      });
    

    您也可以使用Batched Writes 而不是运行多个承诺。

    const updatesBatch = db.batch()
    querySnapshot.forEach(function (docu) {
          const docuRef = db.collection(`organisations/${context.params.orgId}/people`).doc(docu.id) 
          updatesBatch.update(docuRef, {"isDeleted": true});
        });
    })
    updatesBatch.commit().then(() => console.log("Updated"))
    

    如果没有与您的查询匹配的文档,那么您正在查找的参考文献中可能存在任何不匹配。

    【讨论】:

    • 我认为这可能确实是参考文献不匹配。我添加了我当前使用的代码和日志。也许这会提供更多信息?
    • @ThomasSmeman 是的,您在 people 子集合的文档中的 childOrgReference 字段中存储了错误的引用。它应该是 organisations/3dkI69YGRE20AMn9oNGL/childOrganisations/bunEfTrEjtNxaBlpT2zk 否则引用是 childOrganisations 作为根级集合,而不是 organisations. 内部的子集合
    【解决方案2】:

    正如@Dharmaraj 所说,人员文档中的 childOrgReference 不正确。我通过在子集合上而不是在完整路径上查询来解决这个问题。所以我的工作代码是这样的:

    const childOrgReference = db.collection(`childOrganisations`).doc(context.params.childOrgId);
        logger.log(childOrgReference);
    
        // Find all people with corresponding childOrgReference
        db.collection(`organisations/${context.params.orgId}/people`)
            .where("childOrgReference", '==', childOrgReference)
            .get()
            .then(function(querySnapshot) {
              const updates = [];
              querySnapshot.forEach(function(docu) {
                logger.log(docu.id);
                const docuRef = db.collection(`organisations/${context.params.orgId}/people`).doc(docu.id);
                updates.push(docuRef.update({"isDeleted": true}));
              });
    
              Promise.all(updates).then(() => {
                console.log("Documents Updated");
              }).catch((e) => console.log(e));
            });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-12
      • 2018-07-07
      • 2019-01-16
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多