Why is FireStore where query not working?

Viewed 10037

FireStore where is not working or I am doing something wrong. I am trying to user by email: tolotra@tolotra.com

Here is the code:

const admin = require('firebase-admin');
var serviceAccount = require('../secret/nicecode-e3e53-2ddaa9d588ea.json');
admin.initializeApp({
    credential: admin.credential.cert(serviceAccount)
});
var db = admin.firestore();
const settings = {/* your settings... */ timestampsInSnapshots: true};
db.settings(settings);



function begin(email){
    return new Promise(function (res,rej){
        var ans

        var citiesRef = db.collection('users');
        var allCities = citiesRef.get()
            .then(snapshot => {
                snapshot.forEach(doc => {
                    console.log(doc.id, '=>', doc.data());
                });
            })
            .catch(err => {
                console.log('Error getting documents', err);
            });

        var citiesRef = db.collection('users');
        console.log(email)
        var query = citiesRef.where('email', '==', email).get()
            .then(doc => {
                if (!doc.exists) {
                    ans = {
                        "login_token": "7705cb58bbff3afa888a624747f8d1caaff08f6ed0dc465c7d2361fd62532bd7",
                        "next": "FAILURE",
                        "failure_step": {
                            "heading": "Error",
                            "description": "There is no account registered for "+email,
                            "actions": [{"label": "Sign up", "url": "/en/signup"}, {
                                "label": "Sign in",
                                "url": "/en/login"
                            }]
                        }
                    }

                } else {
                    console.log('Document data:', doc.data());
                    ans = {
                        "login_token": "cd01b73935b9262ac8a2bac3f81b6ed6ec78c15d3da5fc04f03879ebdd6931a9",
                        "next": "PASSWORD",
                        "password_step": {"heading": "Password", "description": "Enter your password", "error": ""}
                    }
                }
                res(ans)
            })
            .catch(err => {
                console.log('Error getting document', err);
            });
    })
}

begin('tolotra@tolotra.com').then(function (data) {
console.log(data)
})

Outputs this. (Notice that the user with email 'tolotra@tolotra.com' is found if I just fetch all users)

tolotra@tolotra.com
{ login_token: '7705cb58bbff3afa888a624747f8d1caaff08f6ed0dc465c7d2361fd62532bd7',
  next: 'FAILURE',
  failure_step: 
   { heading: 'Error',
     description: 'There is no account registered for tolotra@tolotra.com',
     actions: [ [Object], [Object] ] } }
OqClQYBH8PWiNE2VF193 => { email: 'tolotra@tolotra.com',
  password_hash: 'E014231EF9830992D2E367231EEDE99C189B6518CE70E2AB8F414C784257751F' }

Here is my database: enter image description here

2 Answers

When you run a query against Firestore there may be multiple documents that match your conditions. That's why the result you get is not a Document, but a QuerySnapshot. And (unlike Document) QuerySnapshot does not have an exists() method, but it does have an empty property that you can use.

So:

var query = citiesRef.where('email', '==', email).get()
    .then(querySnapshot => {
        if (querySnapshot.empty) {
            ans = {
                "login_token": "7705cb58bbff3afa888a624747f8d1caaff08f6ed0dc465c7d2361fd62532bd7",
                "next": "FAILURE",
                "failure_step": {
                    "heading": "Error",
                    "description": "There is no account registered for "+email,
                    "actions": [{"label": "Sign up", "url": "/en/signup"}, {
                        "label": "Sign in",
                        "url": "/en/login"
                    }]
                }
            }

        } else {
            var doc = querySnapshot.docs[0];
            console.log('Document data:', doc.data());
            ans = {
                "login_token": "cd01b73935b9262ac8a2bac3f81b6ed6ec78c15d3da5fc04f03879ebdd6931a9",
                "next": "PASSWORD",
                "password_step": {"heading": "Password", "description": "Enter your password", "error": ""}
            }
        }
        res(ans)
    })
    .catch(err => {
        console.log('Error getting document', err);
    });

The issue is that you are using

.where('email', '==', email).get()

Which implies that it's going to return an array.

However, You are using

!doc.exists

Which does not exist on

.where

You'll need to use

const query = firebase
  .firestore()
  .collection("users")
  .where("email", "==", email).get()
  .then(snapshot => {

    if (snapshot.empty) {
    // No Results
    }

    snapshot.docs.forEach(document => {
     if (document.exists) {
       // Do Something
     } else {
       // Do Something Else
     }
    })
  })
Related