是否可以在firebase数据库引用路径上定义变量?

问题描述 投票:0回答:1

我正在尝试重新定义我的所有应用程序数据库引用,以便我可以编写一组特定的firebase规则(我需要在用户节点内添加建筑物和depts节点 - 阅读原因:What is the best practice to write the rules of Firebase in a situation like this?)。

我正在使用firebase-config.js并将我的应用程序的所有数据库引用导出到应用程序的组件,所以希望如果我更改此路径,我不必重构所有应用程序组件上的代码。

我正在尝试使用函数(在我的firebase-config.js文件中):

import * as firebase from "firebase";
import { mapState } from 'vuex';
import { store } from './store/store';


var config = {
    apiKey: "XXXXXXXX",
    authDomain: "XXXXXXXX.firebaseapp.com",
    databaseURL: "https://XXXXXXXX.firebaseio.com",
    projectId: "XXXXXXXX",
    storageBucket: "XXXXXXXX.appspot.com",
    messagingSenderId: "XXXXXXXX"
};
firebase.initializeApp(config)
export default !firebase.apps.length ? firebase.initializeApp(config) : firebase;

firebase.auth().onAuthStateChanged((user) => {
    if (user) {
       let userRef = firebase.database().ref('users').child(user.uid);
       let buildingsRef = userRef.child('buildings'); 
    }
})();
export const db = firebase.database(); 
export const usersRef = db.ref('users');
_// BUT THIS: "buildingsRef" is returning undefined!!! :(
export const buildingsRef = db.ref('users'+ "/" + buildingsRef) //buildingsRef is a variable
export const deptsRef = db.ref('depts');

buldingsRef变量返回undefined,它将建筑物写入未定义的节点。

{
  "users" : {
    "6hwNde08Wuaa9bfReR28niSbOsF3" : {
      "name" : "João Alves Marrucho",
      "userEmail" : "[email protected]"
    },
    "undefined" : {
      "-L9M4lM7oZFfmJKorxjC" : {
        "address" : "",
        "name" : "b1",
        "ownerID" : "6hwNde08Wuaa9bfReR28niSbOsF3"
      }
    }
  }
}

我使用以下方法(vue.js)写入节点:

addBuilding: function () {
  let userId = firebase.auth().currentUser.uid;
  let buildingKey = buildingsRef.push().key
  this.newBuilding.ownerID = userId;
  buildingsRef.child(buildingKey).set(this.newBuilding);
}

关于为什么变量buildingsRef返回未定义的任何想法?

这是我的完整firebase-config.js文件:http://jsfiddle.net/UnXrw/85/

javascript firebase firebase-realtime-database vue.js
1个回答
0
投票

如果我理解你的问题,我想你想要这样的事情:

firebase.auth().onAuthStateChanged(user => {
  if (user) {
    let userRef = firebase.database().ref('users').child(user.uid);
    let buildingsRef = userRef.child('buildings');
    // now do whatever you want with those refs
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.