fonzane
fonzane

Reputation: 440

Firebase query example returns useless object

I'm trying to get the example from the firebase documentation using queries to work but it doesn't seem to work. I'm using cloud firestore.

This is the result I get: query result

var citiesRef = db.collection("cities");

citiesRef.doc("SF").set({
    name: "San Francisco", state: "CA", country: "USA",
    capital: false, population: 860000,
    regions: ["west_coast", "norcal"] });
citiesRef.doc("LA").set({
    name: "Los Angeles", state: "CA", country: "USA",
    capital: false, population: 3900000,
    regions: ["west_coast", "socal"] });
citiesRef.doc("DC").set({
    name: "Washington, D.C.", state: null, country: "USA",
    capital: true, population: 680000,
    regions: ["east_coast"] });
citiesRef.doc("TOK").set({
    name: "Tokyo", state: null, country: "Japan",
    capital: true, population: 9000000,
    regions: ["kanto", "honshu"] });
citiesRef.doc("BJ").set({
    name: "Beijing", state: null, country: "China",
    capital: true, population: 21500000,
    regions: ["jingjinji", "hebei"] });


// Create a reference to the cities collection
var citiesRef = db.collection("cities");

// Create a query against the collection.
var query = citiesRef.where("state", "==", "CA");

console.log(query);

I'm expecting to log an object that represents the doc that contains the specified value. But the result always is the same (see attachment), even if I search for a non existing value. Why is that? I hope someone can explain whats happening here and why the example that is provided in the documentation isn't working...

Upvotes: 1

Views: 63

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83058

This is because, with the code in your question, you define (and console.log()) a Query object.

You are actually not supposed to directly use this object, but instead:

  • Call the get() method to execute the query and get the resulting documents (through a QuerySnapshot);
  • Attach a listener for QuerySnapshot events, with the onSnapshot() method

  • Or, refine this query with other methods like where(), orderBy(), etc...

You will find the full documentation here: https://firebase.google.com/docs/reference/js/firebase.firestore.Query

So, more concretely, with your current code, you should do something like:

var query = citiesRef.where("state", "==", "CA");

query.get()
  .then(snapshot => {
    if (!snapshot.empty) {
        snapshot.forEach(doc => {
          console.log(doc.id, '=>', doc.data());
        });
    } else {
        console.log('No document corresponding to the query');
    } 
  })
  .catch(err => {
     console.log('Error getting documents', err);
  });

Upvotes: 2

Related Questions