使用触发器向Firebase实时数据库添加元素

时间:2019-04-21 07:21:57

标签: javascript firebase firebase-realtime-database

在数据库上创建字段时,我正在使用Firebase云功能来触发数据库更新。

exports.dbTest2 = functions.database.ref('/{uid}/ignore')
    .onCreate((snapshot, context) => {

        const uid = context.params.uid
        console.log(`Current User ${uid}`)

        // Data added at the location
        const ignoreData = snapshot.val()
        const endTime = new Date(ignoreData.endTime).toString()


        // ref matches `/{uid}/ignore`
        return snapshot.ref.parent.child('schedule').set({

                allDay: false,
                endDate: new Date().toString(),
                id: 100,
                startDate: new Date().toString(),
                title: 'test'

         })

    });

当我将ignore添加到实时数据库中时,将触发此函数。触发后,如下所示:

enter image description here

但是,我希望ignore是一个类似数组的结构,该结构具有索引,每个索引都包含对象。像这样:

我也尝试过类似return snapshot.ref.parent.child('schedule').child().set(...

的操作

但没有用,因为child()需要一个参数。

有帮助吗?

1 个答案:

答案 0 :(得分:1)

您可以简单地传递带有对象的数组:

 return snapshot.ref.parent.child('schedule').set(
  [
    {
        allDay: false,
        endDate: new Date().toString(),
        id: 100,
        startDate: new Date().toString(),
        title: 'test1'
    },
    {
        allDay: false,
        endDate: new Date().toString(),
        id: 101,
        startDate: new Date().toString(),
        title: 'test2'
    }
  ]
 );

在我的firebase中的外观(照片作为数组传递):firebase collection