1

I using firebase on project and write by nodejs. I have method write nodejs get all document in collection user by phone.

const phone = await admin.firestore().collection('users').where('phone_number', '==', phone).get()

Now i want filter if any document by phone not have field deleted_at i return it. Because firebase not support undefined by where i must write function filter it. This is my function

const doc = await getId(phone)

async function getId(phone) {
    var result = null;
    phone.docs.map(async doc => {
            if (doc.exists && doc.data().deleted_at === undefined) {
                result =  doc
            }
        }
    )
    return result
}

When i using console log await getId(phone). It alway return me undefined. But when i change to doc.id it return me correct id i want. I have a question : How to return correct doc in collection. When it returns a doc , I can use it normally such as :

doc.ref.collection("Some sub collection on doc") 

without re querying : await admin.firestore().collection('users').where('phone_number', '==', phone).get() firebase by phone number ?

BaoTrung Tran
  • 392
  • 2
  • 6
  • 21

1 Answers1

2

A few issues here:

  1. Nothing in getId() is asynchronous, so you don't need async/await there.
  2. If you're trying to filter, it probably makes sense to use filter rather than map
  3. Your database query returns a QuerySnapshot not the documents themselves. You can access the documents via the docs property.

Try this:

const userSnapshot = await admin.firestore().collection('users').where('phone_number', '==', phone).get();
    
const myUserDocs = getUndeletedUsers(userSnapshot);

function getUndeletedUsers(userSnapshot) {
    return userSnapshot.docs.filter((doc) => doc.exists && doc.data().deleted_at === undefined);
}
Tim
  • 2,843
  • 13
  • 25
  • Thanks you. So when i get success doc, I can use it normally such as doc.ref.collection("Some sub collection on doc") without re querying : await admin.firestore().collection('users').where('phone_number', '==', phone).get() firebase by phone number ? – BaoTrung Tran Jan 31 '22 at 08:06
  • @BaoTrungTran - You won't have to requery the root collection, but if you want to get the subcollection data for each filtered document, you _will_ need to iterate over the documents and run another query for each document's subcollection. Firestore queries are shallow, meaning you only get the data at the level at which you're querying, not any subcollections. See [this question](https://stackoverflow.com/questions/55632268/firestore-does-querying-a-collection-also-includes-their-sub-collection) for more details. – Tim Jan 31 '22 at 16:11