【问题标题】:how to embed firestore documents into a map in a field of another document?如何将firestore文档嵌入到另一个文档字段中的地图中?
【发布时间】:2020-01-18 08:08:44
【问题描述】:

我有事件集合,我查询了即将开始的 4 个事件。所以我使用这段代码来获取这 4 个事件

const willStartSoonEventsSnapshot = await db.collection('events')
        .where("createdBy","==", event.createdBy)
        .where("isActive","==", true)
        .where("hasBeenApproved","==", true)
        .where("dateTimeStart",">",now)
        .limit(4)
        .orderBy("dateTimeStart","asc")
        .get()

然后,我想将这 4 个事件文档嵌入到用户文档中名为 upcomingEvents 的字段中,这是一个 Map,结果应该是这样的

但我很困惑如何将这 4 个事件快照嵌入到另一个类似文档的字段中?

await db.doc(`users/${uid}`).update({
    upcomingEvents : ..... //map here
})

【问题讨论】:

    标签: node.js firebase google-cloud-firestore


    【解决方案1】:

    以下应该可以解决问题。我们使用forEach() 方法循环查询结果并使用square brackets notation 构建一个JavaScript 对象。

      const willStartSoonEventsSnapshot = await db
        .collection('events')
        .where('createdBy', '==', event.createdBy)
        .where('isActive', '==', true)
        .where('hasBeenApproved', '==', true)
        .where('dateTimeStart', '>', now)
        .limit(4)
        .orderBy('dateTimeStart', 'asc')
        .get();
    
      let upcomingEvents = {};
    
      willStartSoonEventsSnapshot.forEach(doc => {
        upcomingEvents[doc.id] = {
          city: doc.data().city,
          title: doc.data().title
        };
      });
    
      await db.doc(`users/${uid}`).update({
        upcomingEvents
      });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多