同时写入两个数据库引用

时间:2018-08-03 19:42:28

标签: javascript firebase firebase-realtime-database

我有一个Firebase网络应用程序作为注册系统。用户注册课程时,课程数据将作为回调函数的一部分添加到其所有注册的列表中。当用户注册时,最新的类将在列表中重复。在页面加载时,每个课程仅列出一次。

实时数据库结构

{
  courses: {
    courseIdA: {
      // course data
    },
    couseIdB ... {}
  },
  users: {
    uid: {
      regs: {
        courseIdA: true
      }
    }
  }
}

当用户注册时,他们既作为member object被添加到课程ID,又被添加到users下的uid对象中。回调触发两次,因为我正在写courses引用。有没有办法同时写两个?还是我需要为数据库提出一个更好的结构?

获取课程,听更改

users

注册

PDReg.prototype.getAllClasses = function() {
  this.database = firebase.database()
  var uid = firebase.auth().currentUser.uid;
  var courses = [];
  var today = new Date().toISOString();

  this.classesRef = this.database.ref('courses');
  this.userRef = this.database.ref('users/' + uid + "/regs");

    var setClass = function(snapshot) {
      var course = snapshot.val();
      course.key = snapshot.key;

      // check for the current user in a course
      if(course.members) {

        if(course.members.hasOwnProperty(uid)) {

          // This callback fires twice when someone registers
          this.buildUserClasses(course);
        } else {
          this.buildAllClasses(course)
        }
      } else {
        this.buildAllClasses(course)
      }
    }.bind(this);

    // listen for changes to the classes database, rebuild the UI
    this.classesRef.orderByChild('start').startAt(today).on('child_added', setClass);
    this.classesRef.on('child_changed', setClass);
};

0 个答案:

没有答案