【问题标题】:Check if Cloud Firestore query returns something检查 Cloud Firestore 查询是否返回某些内容
【发布时间】:2019-06-29 17:01:35
【问题描述】:

假设我的 Cloud Firestore 如下所示:

users
  ├────random_id_1───{name, email, ...}
  ├────random_id_2───{name, email, ...}
 ...
  └────random_id_n───{name, email, ...}

我创建了一个CollectionReference

var collectionReference = db.collection("users");

然后我创建了一个Query

var query = collectionReference.where("name", "==", "John");

我的目标是检查查询是否找到了某些东西,我只想要这个答案(这样我就可以在 if-else 语句中使用它)。

如果可能,我不想使用这种方法,即使它有效:

query.get().then(function(querySnapshot) {
    if (querySnapshot.empty) {
        console.log('no documents found');
    } else {
        // do something with the data
    }
});

给出一个关于查询的简单布尔值的代码太多了。

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    您分享的是检查文档是否存在的惯用方法,因此没有更好的选择。

    我唯一能想到的是,如果您在支持async/await 的环境中,您可以这样做:

    let querySnapshot = await query.get();
    if (querySnapshot.empty) {
        console.log('no documents found');
    } else {
        // do something with the data
    }
    

    您甚至可以将前两行压缩为:

    if ((await query.get()).empty) {
      ...
    

    不过,我不太喜欢这最后一次机会。像这样隐藏复杂性总是会在某些时候成为泄漏的抽象。

    【讨论】:

    • 好吧,我会坚持惯用的方法...... PS:我知道你会回答嘿嘿:)
    猜你喜欢
    • 1970-01-01
    • 2018-08-15
    • 2011-10-11
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    • 1970-01-01
    相关资源
    最近更新 更多