150

I want to query a firestore database for document id. Currently I have the following code:

db.collection('books').where('id', '==', 'fK3ddutEpD2qQqRMXNW5').get()

I don't get a result. But when I query for a different field it works:

db.collection('books').where('genre', '==', 'biography').get()

How is the name of the document id called?

André Kool
  • 4,880
  • 12
  • 34
  • 44
Developer
  • 2,113
  • 2
  • 18
  • 26

11 Answers11

321

I am a bit late, but there is actually a way to do this

db.collection('books').where(firebase.firestore.FieldPath.documentId(), '==', 'fK3ddutEpD2qQqRMXNW5').get()

This might be useful when you're dealing with firebase security rules and only want to query for the records you're allowed to access.

Denys Mikhalenko
  • 3,966
  • 2
  • 14
  • 18
131

Try this:

db.collection('books').doc('fK3ddutEpD2qQqRMXNW5').get()

(The first query is looking for an explicit user-set field called 'id', which probably isn't what you want.)

Todd Kerpelman
  • 16,875
  • 4
  • 42
  • 40
  • 4
    Hey do you know how to get document ID that obeys some condition mentioned in a query in firestore – Divya Galla Jan 02 '18 at 08:47
  • 60
    What to do if we need multiple where case (multiple id)? – Midhilaj May 19 '19 at 11:13
  • 11
    In python I get `AttributeError: 'CollectionReference' object has no attribute 'doc'`. Turns out the syntax there is `db.collection('books').document('longid').get()` – szeitlin Jun 27 '19 at 00:01
  • @Midhilaj : could it be that document id's are unique? – gusgonnet Aug 14 '20 at 01:49
  • 1
    @Midhilaj in my case i have another collection where i have document of each user which store the data that satisfy a specific condition. i have very limited conditions e.g what book is uploaded by which user. – Abdul Wahid Mar 14 '21 at 09:32
68

You can use the __name__ key word to use your document ID in a query.

Instead of this db.collection('books').doc('fK3ddutEpD2qQqRMXNW5').get() you can write

db.collection('books').where('__name__', '==' ,'fK3ddutEpD2qQqRMXNW5').get().

In this case you should get an array of length 1 back.

The firebase docs mention this feature in the rules documentation. https://firebase.google.com/docs/reference/rules/rules.firestore.Resource

Jürgen Brandstetter
  • 7,066
  • 3
  • 35
  • 30
  • 1
    This is handy when using the Firestore UI in prod or in the emulator, where you can't use something like `db.collection('foo').doc('xxxx')` – John Gordon Jul 10 '20 at 18:09
  • 1
    This is what I needed on my cloud function implementation, client sends the doc ids and I need to query all docs with "in" and get docs – Divyanshu Negi Oct 16 '20 at 08:18
  • Thanks mate, that´s the information I was looking for! – codingbuddha Nov 29 '20 at 15:55
  • @DivyanshuNegi The admin SDK has a `getAll()` function https://googleapis.dev/nodejs/firestore/latest/Firestore.html#getAll I think this what you are looking for. Right? – Jürgen Brandstetter Dec 02 '20 at 09:33
  • @JohnGordon Unfortunately the Firebase Web UI doesn't let me create a query with `__name__`. The apply button is just greyed out :( – Sven Jacobs Sep 15 '21 at 10:10
  • Thanks for the example, I would have never realized it could be used that way from the documentation, tried it with the php sdk and it works. – Alex Sep 28 '21 at 17:22
48

June, 2021

The new v9 modular sdk is tree-shakeable and results in smaller compiled apps. It is recommended for all new Firestore apps.

import { doc, getDoc } from "firebase/firestore";

const snap = await getDoc(doc(db, 'books', 'fK3ddutEpD2qQqRMXNW5'))

if (snap.exists()) {
  console.log(snap.data())
}
else {
  console.log("No such document")
}

This is based on the example from the firestore docs

import { doc, getDoc } from "firebase/firestore";

const docRef = doc(db, "cities", "SF");
const docSnap = await getDoc(docRef);

if (docSnap.exists()) {
  console.log("Document data:", docSnap.data());
}
else {
  // doc.data() will be undefined in this case
  console.log("No such document!");
}

You could make this into a helper function

async function getDocument (coll, id) {
  const snap = await getDoc(doc(db, coll, id))
  if (snap.exists())
    return snap.data()
  else
    return Promise.reject(Error(`No such document: ${coll}.${id}`))
}

getDocument("books", "fK3ddutEpD2qQqRMXNW5")
Mulan
  • 129,518
  • 31
  • 228
  • 259
29

While everyone is telling to use .get(), which is totally reasonable but it's not always the case.

Maybe you want to filter data based on id (using a where query for example).

This is how you do it in Firebase v9 modular SDK:

import {collection, documentId} from 'firebase/firestore'

const booksRef = collection('books')

const q = query(booksRef, where(documentId(), '==', 'fK3ddutEpD2qQqRMXNW5'))
Syed Basim
  • 326
  • 3
  • 3
15

You can get a document by its id following this pattern:

firebase
  .firestore()
  .collection("Your collection")
  .doc("documentId")
  .get()
  .then((docRef) => { console.log(docRef.data()) })
  .catch((error) => { })
j3ff
  • 5,719
  • 8
  • 38
  • 51
Venkat
  • 347
  • 3
  • 13
9

Currently only working way for Cloud Functions if you really need to use this way:

// Import firebase-admin
import * as admin from "firebase-admin";

// Use FieldPath.documentId()
admin.firestore.FieldPath.documentId()

 const targetUser = await db.collection("users").where(admin.firestore.FieldPath.documentId() "==", "givenId").get();

Simpler way of this is directly using ID value thru path as there is only one document with given document ID:

const targetUser = await db.doc("users/"+ "givenId").get();

However, you may really need to use it if you are matching given IDs array to the Firebase collection like this:

const admin = require("firebase-admin");

const arr = ["id1", "id2"];
const refArr = arr.map(id => admin.firestore().collection("media").doc(id));

const m = await admin
      .firestore()
      .collection("media")
      .where(admin.firestore.FieldPath.documentId(), "in", refArr)
      .get();

This last example is from this discussion

Elmar
  • 2,235
  • 24
  • 22
2

If you are looking for more dynamic queries with a helper function, you can simply try this.

import { db} from '@lib/firebase';

import {query, collection, getDocs ,documentId } from "firebase/firestore";

const getResult = async (_value) => {
     const _docId = documentId()
     const _query = [{
        field: _docID,
        operator: '==',
        value: _value
      }]
// calling function
    const result = await getDocumentsByQuery("collectionName", qColl)
    console.log("job result: ", result) 
}

// can accept multiple query args
const getDocumentsByQuery = async (collectionName, queries) => {
    const queryArgs = [];
    queries.forEach(q => {
        queryArgs.push(
            where(q.field, q.operator, q.value)
        );
    });

    const _query = query(collection(db, collectionName), ...queryArgs);
    const querySn = await getDocs(_query);
   
   const documents = [];
    querySn.forEach(doc => {
        documents.push({ id: doc.id, ...doc.data() });
    });

    return documents[0];
};
Fred
  • 1,103
  • 2
  • 14
  • 35
MickyTonji
  • 21
  • 2
1

From Firestore docs for Get a document.

var docRef = db.collection("cities").doc("SF");

docRef.get().then(function(doc) {
    if (doc.exists) {
        console.log("Document data:", doc.data());
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});
John
  • 94
  • 10
1

This is the first link that came up when I was looking to solve it in the Golang SDK, so I'll add my solution in case anyone else is looking for it:

package main

import (
    "context"
    "fmt"
    "log"

    "cloud.google.com/go/firestore"
    firebase "firebase.google.com/go/v4"
    "google.golang.org/api/option"
)

type (
    Car struct {
        ID    string
        Name  string  `firestore:"name"`
        Make  string  `firestore:"make"`
        Price float64 `firestore:"make"`
    }
)

func main() {
    ctx := context.Background()

    // Use a service account
    options := option.WithCredentialsFile("PATH/TO/SERVICE/FILE.json")

    // Set project id
    conf := &firebase.Config{ProjectID: "PROJECT_NAME"}

    // Initialize app
    app, err := firebase.NewApp(ctx, conf, options)
    if err != nil {
        log.Fatal(err)
    }

    // Get firestore client
    client, err := app.Firestore(ctx)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    collectionRef := client.Collection("CAR_COLLECTION")

    // firestore.DocumentID == "__name__" 
    docSnap, err := collectionRef.Where(firestore.DocumentID, "==", collectionRef.Doc("001")).Get(ctx)
    if err != nil {
        log.Fatal(err)
    }

    // Unmarshall item
    car := Car{}
    docSnap.DataTo(&car)
    car.ID = docSnap.Ref.ID

    // Print car list
    fmt.Println(car)
}
Carlo Nyte
  • 665
  • 6
  • 17
0

Just to clear confusion here

Remember, You should use async/await to fetch data whether fetching full collection or a single doc.

async function someFunction(){
 await db.collection('books').doc('fK3ddutEpD2qQqRMXNW5').get();
}
Mejan
  • 918
  • 13
  • 18