简体   繁体   English

查询文件 ID 的 firestore 数据库

[英]Query firestore database for document id

I want to query a firestore database for document id.我想在 Firestore 数据库中查询文档 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?文档id的名字怎么叫?

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.当您处理 firebase 安全规则并且只想查询您被允许访问的记录时,这可能很有用。

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.) (第一个查询是寻找一个名为“id”的显式用户设置字段,这可能不是您想要的。)

You can use the __name__ key word to use your document ID in a query.您可以使用__name__关键字在查询中使用您的文档 ID。

Instead of this db.collection('books').doc('fK3ddutEpD2qQqRMXNW5').get() you can write而不是这个db.collection('books').doc('fK3ddutEpD2qQqRMXNW5').get()你可以写

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

In this case you should get an array of length 1 back.在这种情况下,您应该得到一个长度为1的数组。

The firebase docs mention this feature in the rules documentation. firebase 文档在规则文档中提到了此功能。 https://firebase.google.com/docs/reference/rules/rules.firestore.Resource https://firebase.google.com/docs/reference/rules/rules.firestore.Resource

June, 2021 2021 年 6 月

The new v9 modular sdk is tree-shakeable and results in smaller compiled apps.新的v9 模块化 sdk可摇树并生成更小的编译应用程序。 It is recommended for all new Firestore apps.建议用于所有新的 Firestore 应用程序。

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这是基于firestore 文档中的示例

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")

You can get a document by its id following this pattern:您可以按照以下模式通过其id获取文档:

firebase
  .firestore()
  .collection("Your collection")
  .doc("documentId")
  .get()
  .then((docRef) => { console.log(docRef.data()) })
  .catch((error) => { })

While everyone is telling to use .get() , which is totally reasonable but it's not always the case.虽然每个人都在告诉使用.get() ,这是完全合理的,但并非总是如此。

Maybe you want to filter data based on id (using a where query for example).也许您想根据id过滤数据(例如使用where查询)。

This is how you do it in Firebase v9 modular SDK:这就是您在 Firebase v9 模块化 SDK 中的操作方式:

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

const booksRef = collection('books')

const q = query(booksRef, where(documentId(), '==', 'fK3ddutEpD2qQqRMXNW5'))

From Firestore docs for Get a document.Firestore 文档获取文档。

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);
});

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 = documented()
     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];
};

Just to clear confusion here只是为了清除这里的混乱

Remember, You should use async/await to fetch data whether fetching full collection or a single doc .请记住,您应该使用async/await来获取数据,无论是获取完整collection还是单个doc

async function someFunction(){
 await db.collection('books').doc('fK3ddutEpD2qQqRMXNW5').get();
}

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:这是我希望在 Golang SDK 中解决它时出现的第一个链接,因此我将添加我的解决方案以防其他人正在寻找它:

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)
}

Currently only working way for Cloud Functions if you really need to use this way:如果您确实需要使用这种方式,目前仅适用于 Cloud Functions:

// 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:更简单的方法是通过路径直接使用 ID 值,因为只有一个具有给定文档 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:但是,如果您将给定的 IDs 数组与 Firebase 集合匹配,您可能真的需要使用它,如下所示:

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最后一个例子来自这个讨论

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM