Prateek Pareek
Prateek Pareek

Reputation: 170

how to get document id in fire base for specific field value

exports.getref = (oid, successFunc, errFunc) => {
    dbconfig.collection('txn')
        .where('oid', '==', oid)
        .get()
        .then(docRef => {
            successFunc({
                id: docRef.id,
                success: true
            })
        })
        .catch(err => {
            errFunc({ id: null, success: false })
        })

here I want to get document id of my collection where field value oid equals oid . how i can get doc id

Upvotes: 0

Views: 1045

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317402

When you perform a query with Firestore, you get back a QuerySnapshot object, no matter how many documents match the query.

dbconfig.collection('txn')
    .where('oid', '==', oid)
    .get()
    .then(querySnapshot => { ... })

You have to use this QuerySnapshot to find out what happened. I suggest reading the linked API documentation for it.

You should check to see if it contains any documents at all with the size method, then if it has the document you're looking for, use the docs array to find the DocumentSnapshot with the data. That snapshot will have a DocumentReference property with the id:

if (querySnapshot.size == 1) {
    const snap = querySnapshot.docs[0];
    console.log(snap.ref.id);
}
else {
    console.log("query result in exactly one document");
}

Upvotes: 2

Related Questions