【问题标题】:How do I copy a node(object) in Firebase to another node?如何将 Firebase 中的节点(对象)复制到另一个节点?
【发布时间】:2017-02-06 08:04:44
【问题描述】:

我在 Firebase 中有一个名为 Events 的节点。它由子对象组成,例如:addressdescriptionlongitudelatitude。在用户删除事件节点之前,我想将其复制到同一个数据库中的一个名为 eventsDeleted 的节点中。

这是删除节点的代码:

removeEvent(eventId, groupId) {

  return new Promise((resolve, reject)=> {

    this.eventRef.child(groupId).child(eventId).remove();
    resolve();

  });

}

这是创建节点的代码:

addEvent(data:any) {
    console.log('Form data', data.group);

    let localEventRef = firebase.database().ref('events').child(data.group.split(',')[1]);
    let storageRef = firebase.storage().ref();
    let file = data.image;
    let uploadTask = storageRef.child('eventImages/' + UuidGenerator.generateUUID()).put(file);
    uploadTask.on('state_changed', function (snapshot) {

    }, function (error) {
        // Handle unsuccessful uploads
        console.error(error);
    }, function () {
        // Handle successful uploads on complete
        let downloadURL = uploadTask.snapshot.downloadURL;
        let keyOfNewEvent = localEventRef.push(
            new Event(
                null,
                firebase.app().auth().currentUser.uid,

                data.description,


                data.location.address,
                0

            )
        ).key;
        localEventRef.child(keyOfNewEvent).update({eventId: keyOfNewEvent});
    });


}

不要介意上传图片的代码。如果可能的话,我只需要一种方法来复制整个节点,然后将其粘贴到数据库中的某个位置。提前致谢。

【问题讨论】:

标签: javascript angularjs firebase firebase-realtime-database


【解决方案1】:

当用户单击删除时,请确保获取正在删除的对象,如果您要在数据库中查询该对象,您可以使用 .once 检索该对象,否则您可以直接跳转到 removeEvent直接运行。

localEventRef.child(keyOfEvent).once("value", function(snapshot) {
 //one data is returned, you can then call the removeEvent fn

  let eventToBeRemoved = snapshot.val();
  //assuming you have the eventid, groupid then. 
  removeEvent(eventId, groupId, eventToBeRemoved);
});

removeEvent(eventId, groupId, eventObjectToBeRemoved) {
//firebase 3.x comes with a promise method

    firebase.database().ref('eventsDeleted/' + groupId + '/' + eventId )
      .set({...eventObjectToBeRemoved})
      .then(function () { 
        eventRef.child(groupId).child(eventId).remove();//you can now remove
      })
      .catch(function (error) {
        console.error("error occured trying to add to deletedEvents", error);
      });
    });
}

【讨论】:

  • 我无法按原样执行此代码,对不起。我能够将代码的前三行放入 removeEvent() 函数中。我跑了,我能够像以前一样删除事件,但它没有像我希望的那样在数据库上创建一个名为“eventsDeleted”的节点,其中包含数据。我快到了,只是缺少一些东西。能否进一步提供帮助,谢谢。
  • 哦,我希望您没有在.set 上添加这些.....eventObjectToBeRemoved,因为这只是一个示例?它应该是像 {event: "", id: ""}... 这样的对象
  • 非常感谢您的回复。我可以在 set() 中使用 eventRef.child(groupId).child(eventId) 吗?还是必须是 {event: "", id: ""} ?
  • 或将 eventToBeRemoved 放入集合中?
  • eventToBeRemoved 在集合内@kuhle
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-20
  • 1970-01-01
  • 2017-05-15
  • 1970-01-01
  • 2017-03-20
  • 1970-01-01
  • 2023-02-18
相关资源
最近更新 更多