阵列内部不允许Firebase Firestore时间戳 [英] Firebase Firestore timestamp not allowed inside array

查看:74
本文介绍了阵列内部不允许Firebase Firestore时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于以下的Firestore数据模型

I have a firestore data model like below

board :{
  id: string,
  name: string,
  cratedAt: Timestamp,
  updatedAt: Timestamp,
  owner: string,
  columns: [{
    name: string,
    createdAt: Timestamp,
    updatedAt: Timestamp,
  }]

问题是我无法在数组内添加时间戳,因为Firebase不支持它.因此,我的选择是进行单独的根收集,并将ID的内容存储在列"字段中.数组或去子集合.但这会不会增加读取次数并因此增加我的整体交易的价格/账单?如何避免这种情况?

The problem is I can't add timestamp inside arrays as it isn't supported by firebase. So my options are to go for separate root collection and store the id's inside the "columns" array or go for subcollections. But won't this increase the number of reads and consequently the price/bill of my overall transaction? How do I avoid this?

推荐答案

实际上,无法在数组中添加带有 firebase.firestore.FieldValue.serverTimestamp()的时间戳.有关其原因的更多详细信息,请参见此处.不可能.通常的解决方法是将Array更改为Map.

Indeed it is not possible to add a timestamp with firebase.firestore.FieldValue.serverTimestamp() inside an array. See here for more details on the reason why it is not possible. The usual workaround is to change the Array to a Map.

但是使用Cloud Function还有另一种可能的解决方法:

由于您的文档中有两个保存时间戳的字段( createdAt updatedAt ),因此您可以分配这些字段的值(通过 FieldValue.serverTimestamp())到数组元素,并在创建文档时调用Cloud函数.

Since you have, in your doc, two fields which hold a timestamp (createdAt and updatedAt), you can assign the value of those fields (generated via FieldValue.serverTimestamp()) to the array elements, with a Cloud Function called when the doc is created.

以下Cloud Function代码显示了如何对 columns 数组中的一个元素执行操作.您可以自行调整它以覆盖具有多个元素的数组.

The following Cloud Function code shows how to do for one element in the columns array. It's up to you to adapt it to cover arrays with more than one element.

exports.updateTimeStampsInArray = functions.firestore
    .document('myCollection/{docId}')
    .onCreate((snap, context) => {

        const newValue = snap.data();
        const createdAt = newValue.createdAt;

        const columnsArray = newValue.columns;

        const newColumnsArray = [];
        newColumnsArray.push({ name: columnsArray[0].name, createdAt: createdAt });

        return snap.ref.update({ columns: newColumnsArray })
    });

您需要按以下步骤创建文档:

You need to create the doc as follows:

  db.collection('myCollection')
    .doc('...')
    .set({
      createdAt: firebase.firestore.FieldValue.serverTimestamp(),
      columns: [{ name: 'TheName' }],  
    });

CF一旦运行,它将使用 createdAt 时间戳记的值填充Array元素.

As soon as the CF will run, it will populate the Array element with the value of the createdAt Timestamp.

这篇关于阵列内部不允许Firebase Firestore时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆