Get documents names in Firestore

雨燕双飞 提交于 2019-12-31 04:30:10

问题


When I get several documents from a collection, the result is only an array with each doc data.

firestore.collection("categories").valueChanges().subscribe(data => {
    console.log(data);
    // result will be: [{…}, {…}, {…}]
};

How can I get the name of each doc?

The ideal result would look like this:

{"docname1": {…}, "docname2": {…}, "docname3": {…}}

回答1:


When you need to access additional metadata like the key of your Document, you can use the snapshotChanges() streaming method.

firestore.collection("categories").valueChanges().map(document => {
      return document(a => {
        const data = a.payload.doc.data();//Here is your content
        const id = a.payload.doc.id;//Here is the key of your document
        return { id, ...data };
      });

You can review the documentation for further explanation and example




回答2:


// this prints each document individual 
db.collection("categories")
    .onSnapshot((querySnapshot) => {
        querySnapshot.forEach((doc) => {
            console.log(doc.data()); // For data inside doc
            console.log(doc.id); // For doc name
    }
}


来源:https://stackoverflow.com/questions/47953387/get-documents-names-in-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!