【问题标题】:Firebase Web Automatically insert createdAt and updatedAt fieldsFirebase Web 自动插入 createdAt 和 updatedAt 字段
【发布时间】:2018-02-13 08:05:26
【问题描述】:

我一直在为我的一个项目使用 Firebase,但我注意到它不会像 Mongodb 那样自动添加 createdAt 和 updatedAt 字段。如何在 Google Firebase 中实现相同的功能?我一直在寻找某种可以覆盖以添加字段的事件或函数,但我没有任何运气!

【问题讨论】:

  • 你的意思是 json 对象的 createdOn 和 modifiedOn 日期时间字段?
  • 是的,每次我在数据库中设置一些东西时,我都希望它为我做这件事,所以每次我添加一些东西时,我都不需要不断更新 modifiedOn 和 createdOn 字段

标签: javascript firebase firebase-realtime-database


【解决方案1】:

您可以使用Firebase Cloud Functions. 来实现这一点,请看一下。

下面是示例代码,你可以用它来实现。

exports.generateCreatedOn = functions.database.ref('/messages/{pushId}/')
    .onWrite(event => {
      return event.data.ref.child('createdOn').set(new String(new Date()));
    });

在这里,我将路径设置为/messages/{pushId}/,这会导致重复的函数触发。所以请在下面找到正确的代码,

exports.generateCreatedOn = functions.database.ref('/messages/{pushId}/someKnownKey')
        .onWrite(event => {
          return event.data.ref.parent.child('createdOn').set((new Date()).getTime());
        });

但您必须对所使用的任何路径应用相同的逻辑。而且,我只设置了createdOn,请对modifiedOn使用类似的逻辑。

希望对你有所帮助。

【讨论】:

  • 感谢您的帮助,还有一件事情是 Firebase 中的某些东西可以像 mongoDB 的填充功能一样工作吗?例如填充帖子条目中的用户字段?
  • 我没有尝试过 mongoDB' 填充。如果你解释一下功能,我会尝试用firebase的方式来整理。
  • 一切都很好,我已经想出了如何实现相同的功能
  • mongo 的 populate 函数有点像 sql 中的 join,它允许从引用中获取对象。据我所知,firebase 中没有这样的东西,您需要通过新调用中的引用来请求对象
猜你喜欢
  • 1970-01-01
  • 2018-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多