简体   繁体   中英

Get a document from firestore by name

The firestore docs seem confusing to me. Say I have a set of posts:

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

And I want to get a post with the name Foo .

Following this guide: https://firebase.google.com/docs/firestore/query-data/get-data

It begins with this line: var docRef = db.collection("cities").doc("SF");

I dont 'understand what .doc("SF") means. Is SF an ID? What if my ID was auto-generated? 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?

First, make sure you understand the Cloud Firestore data model . It's not the same as Firebase Realtime Database (formerly known as just Firebase).

If the posts from your example is a collection with two documents, you can use a query to find a document by 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.

You need an index for any kind of query, but this one is simple enough that it will be automatically created for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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