代码之家  ›  专栏  ›  技术社区  ›  Stroi

从Firestore中的一个集合获取所有文档

  •  4
  • Stroi  · 技术社区  · 6 年前

    async getMarkers() {
      const events = await firebase.firestore().collection('events').get()
        .then(querySnapshot => {
          querySnapshot.docs.map(doc => {
            console.log('LOG 1', doc.data());
            return doc.data();
          });
        });
      console.log('LOG 2', events);
      return events;
    }
    

    log1打印所有对象(一个接一个),但是log2没有定义,为什么?

    2 回复  |  直到 6 年前
        1
  •  173
  •   Doug Stevenson    6 年前

    async getMarker() {
        const snapshot = await firebase.firestore().collection('events').get()
        return snapshot.docs.map(doc => doc.data());
    }
    
        2
  •  20
  •   Imanullah    5 年前

    如果你想包括身份证

    async getMarkers() {
      const events = await firebase.firestore().collection('events')
      events.get().then((querySnapshot) => {
          const tempDoc = querySnapshot.docs.map((doc) => {
            return { id: doc.id, ...doc.data() }
          })
          console.log(tempDoc)
        })
    }
    

    与数组相同

    async getMarkers() {
      const events = await firebase.firestore().collection('events')
      events.get().then((querySnapshot) => {
          const tempDoc = []
          querySnapshot.forEach((doc) => {
             tempDoc.push({ id: doc.id, ...doc.data() })
          })
          console.log(tempDoc)
       })
     }
    
        3
  •  7
  •   Stroi    6 年前

    async getMarkers() {
      const markers = [];
      await firebase.firestore().collection('events').get()
        .then(querySnapshot => {
          querySnapshot.docs.forEach(doc => {
          markers.push(doc.data());
        });
      });
      return markers;
    }
    
        4
  •  7
  •   Horai Nuri    5 年前

    如果需要在响应中包含文档的键,另一种选择是:

    async getMarker() {
        const snapshot = await firebase.firestore().collection('events').get()
        const documents = [];
        snapshot.forEach(doc => {
           documents[doc.id] = doc.data();
        });
        return documents;
    }
    
        5
  •  3
  •   OneHoopyFrood    5 年前

    您可以将整个集合作为一个对象,而不是这样的数组:

    async getMarker() {
        const snapshot = await firebase.firestore().collection('events').get()
        const collection = {};
        snapshot.forEach(doc => {
            collection[doc.id] = doc.data();
        });
        return collection;
    }
    

    这会让你更好地展示firestore里的东西。数组没有问题,只是另一种选择。

        6
  •  2
  •   Nowdeen    5 年前

    我更喜欢在我的服务中隐藏所有代码的复杂性。。。所以,我通常用这样的方法:

    在我的事件.service.ts

        async getEvents() {
            const snapchot = await this.db.collection('events').ref.get();
            return new Promise <Event[]> (resolve => {
                const v = snapchot.docs.map(x => {
                    const obj = x.data();
                    obj.id = x.id;
                    return obj as Event;
                });
                resolve(v);
            });
        }
    

    在我的某物第页

       myList: Event[];
    
       construct(private service: EventsService){}
    
       async ngOnInit() {
          this.myList = await this.service.getEvents();
       }
    
    

    享受:)

        7
  •  1
  •   Josh    4 年前

    async getMarker() {
        const snapshot = await firebase.firestore().collection('events').get()
        return snapshot.docs.reduce(function (acc, doc, i) {
                  acc[doc.id] = doc.data();
                  return acc;
                }, {});
    }
    
        8
  •  0
  •   Alok G.    4 年前

    尝试跟踪LOC

        let query = firestore.collection('events');
        let response = [];
        await query.get().then(querySnapshot => {
              let docs = querySnapshot.docs;
              for (let doc of docs) {
                  const selectedEvent = {
                         id: doc.id,
                         item: doc.data().event
                      };
                 response.push(selectedEvent);
              }
       return response;
    
        9
  •  0
  •   r002    4 年前

    虽然晚了两年,但我最近才开始阅读Firestore文档,为了好玩,我发现 withConverter 我看到的答案都没有贴在上面。因此:

    如果你想包括ID 同时使用 带转换器 (Firestore的ORMs版本,比如用于Ruby on Rails的ActiveRecord、用于.NET的Entity Framework等),那么这可能对您很有用:

    Event 正确定义模型。例如,类似于:

    您的模型(英寸) TypeScript ): ./models/Event.js

    export class Event {
      constructor (
        public id: string,
        public title: string,
        public datetime: Date
      )
    }
    
    export const eventConverter = {
      toFirestore: function (event: Event) {
        return {
          // id: event.id,  // Note! Not in ".data()" of the model!
          title: event.title,
          datetime: event.datetime
        }
      },
      fromFirestore: function (snapshot: any, options: any) {
        const data = snapshot.data(options)
        const id = snapshot.id
        return new Event(id, data.title, data.datetime)
      }
    }
    

    打字稿

    import { eventConverter } from './models/Event.js'
    
    ...
    
    async function loadEvents () {
      const qs = await firebase.firestore().collection('events')
        .orderBy('datetime').limit(3)  // Remember to limit return sizes!
        .withConverter(eventConverter).get()
    
      const events = qs.docs.map((doc: any) => doc.data())
    
      ...
    }
    
    

    Firestore的两个有趣的怪癖值得注意(或者至少,我觉得很有趣):

    1. event.id 实际上存储在 snapshot.id snapshot.data()

    const events = qs.docs.map((doc: Event) => doc.data())

    即使你在上面明确指出: .withConverter(eventConverter)

    这就是为什么需要 doc: any .

    ( 你会 得到 Array<Event> Array<Map> ... 这样,如果您有任何对象方法(本例中未显示),就可以立即使用它们。)

    这对我来说是有意义的,但我猜我已经变得如此贪婪/被宠坏了,我只是有点期待我的VS代码、ESLint和TS Watcher会真的这么做 为了我。哦,好吧。


    正式文件(关于 带转换器 https://firebase.google.com/docs/firestore/query-data/get-data#custom_objects