最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check if Cloud Firestore query returns something - Stack Overflow

programmeradmin1浏览0评论

Let's say my Cloud Firestore looks like this:

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

I created a CollectionReference:

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

Then I created a Query:

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

My goal is to check if the query finds something or not, I just want this answer (so I can use it in an if-else statement).

If possible, I don't want to use this approach, even that it works:

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

It's too much code to give a simple boolean about the query.

Let's say my Cloud Firestore looks like this:

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

I created a CollectionReference:

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

Then I created a Query:

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

My goal is to check if the query finds something or not, I just want this answer (so I can use it in an if-else statement).

If possible, I don't want to use this approach, even that it works:

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

It's too much code to give a simple boolean about the query.

Share Improve this question edited Nov 20, 2022 at 14:50 Daniel asked Feb 5, 2019 at 19:35 DanielDaniel 7,7249 gold badges36 silver badges99 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 21

What you've shared is the idiomatic approach to check for the existence of a document, so there aren't any better options.

The only thing I can think of is if you're on an environment that supports async/await in which case you can do this:

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

You could probably even condense the first two lines into:

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

I don't like this last chance all that much though. Hiding complexity like this always ends up being a leaky abstraction at some point.

发布评论

评论列表(0)

  1. 暂无评论