简体   繁体   English

按名称从 firestore 获取文档

[英]Get a document from firestore by name

The firestore docs seem confusing to me. firestore 文档对我来说似乎很混乱。 Say I have a set of posts:假设我有一组帖子:

posts: [{ name: 'Foo' }, { name: 'Bar' }]

And I want to get a post with the name Foo .我想得到一个名为Foo的帖子。

Following this guide: https://firebase.google.com/docs/firestore/query-data/get-data遵循本指南: https : //firebase.google.com/docs/firestore/query-data/get-data

It begins with this line: var docRef = db.collection("cities").doc("SF");它从这一行开始: var docRef = db.collection("cities").doc("SF");

I dont 'understand what .doc("SF") means.我不明白.doc("SF")是什么意思。 Is SF an ID? SF是身份证吗? What if my ID was auto-generated?如果我的 ID 是自动生成的怎么办? I want to fetch data using this method:我想使用这种方法获取数据:

docRef.get().then(function(doc) {
    if (doc.exists) {
      ...
    }
}

But confused about the documentation.但对文档感到困惑。 What's the best way to get() with my data? get()与我的数据的最佳方式是什么?

First, make sure you understand the Cloud Firestore data model .首先,请确保您了解 Cloud Firestore 数据模型 It's not the same as Firebase Realtime Database (formerly known as just Firebase).它与 Firebase 实时数据库(以前称为 Firebase)不同。

If the posts from your example is a collection with two documents, you can use a query to find a document by name :如果示例中的posts是包含两个文档的集合,则可以使用 查询name查找文档:

var query = db.collection("posts").where("name", "==", "Foo");
var querySnapshot = await query.get();

Now querySnapshot will be an array of documents that matched your query.现在querySnapshot将是与您的查询匹配的文档数组。

You need an index for any kind of query, but this one is simple enough that it will be automatically created for you.对于任何类型的查询,您都需要一个 索引,但这个 索引很简单,它会自动为您创建。

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

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