Sony
Sony

Reputation: 7196

Perform a simple select query in Firebase Firestore

How can I perform a simple search in Firebase Firestore to check if a record exists in a collection? I've seen this code in the documentation, but it is not complete.

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

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

In my use case I want to check the rejected contacts collection for a given number. This is my code

const collectionRef = db.collection('rejectedContacts');
    const queryRef = collectionRef.where('contact','==',phone);

    let contactRejected: boolean = queryRef.get.length>0 ;
    if (contactRejected) {
        return response.json(
            {
                status: 0,
                message: `Contact , ${phone} is blocked. Please try again with another one.`,
                result: null
            });
    }

I've checked the function with a rejected number, which i added manually in the collection, but it is not responding with the rejected message. How can I get the count or the row itself with a select query. What is wrong with my code?

UPDATE 1 As @Matt R suggested, I updated the code with this

let docRef = db.collection('rejectedContacts').where('contact', '==', phone).get();
    docRef.then(doc => {
        if (!doc.empty) {
            return response.json(
                {
                    status: 0,
                    message: `Contact , ${phone} is blocked. Please try again with another one.`,
                    result: null
                });
        } else {
            return response.json(
                {
                    status: 0,
                    message: `Contact , ${phone} is not blocked`,
                    result: null
                });
        }
    })
        .catch(err => {
            console.log('Error getting document', err);
        });

But when checked with the existing number, it is returning with not blocked

Edit 2

return collectionRef.select('contact').where('contact', '==', phone).get()
        .then(snapShot => {
            let x : string = '['
            snapShot.forEach(doc => {
                console.log(doc.id, '=>', doc.data());
                x+= `{${doc.data}},`;
            });
            return response.send(x);
        });

It is only returning the value of x from this line

let x : string = '['

Upvotes: 2

Views: 8325

Answers (1)

Matthew Rideout
Matthew Rideout

Reputation: 8518

Firestore's get() method returns a promise and response, I would try in this format to handle whether the document exists or not. This format may also lend better error messages when troubleshooting.

EDIT / UPDATED: Using the where clause returns a snapshot that must be iterated through, because it can return multiple documents. See documentation here: https://firebase.google.com/docs/firestore/query-data/get-data#get_multiple_documents_from_a_collection

Updated code with your example.

var collectionRef = db.collection('rejectedContacts');
var query = collectionRef.where('contact','==',phone).get()
.then(snapshot => {
    snapshot.forEach(doc => {
        console.log(doc.id, '=>', doc.data());
    });
})
.catch(err => {
    console.log('Error getting documents', err);
});

Upvotes: 1

Related Questions