【问题标题】:Get Key for object created after Push (Angular and Firebase)获取推送后创建的对象的密钥(Angular 和 Firebase)
【发布时间】:2018-01-02 13:25:25
【问题描述】:

我在理解如何使用 Firebase 时遇到问题。我编写了一个函数来将一些数据推送到我的 firebase 数据库中。我需要在将数据推送到我的数据库后生成密钥。

这是我的功能

  postData(order: orderInfo) {
    let uid = firebase.auth().currentUser.uid;
    this.db.list('transactions').push({
      currency: order.currency,
      total: order.total,
      rate: order.rate,
      uid: uid
    });
    console.log(order.$key);
    this.db.list('transactionsPerUser').update(uid, order.$key);
  }

当我将数据推送到事务路径时,它还会推送用户 uid,因此我可以将数据从我的用户数据库链接到事务数据库。我现在想要的是在我的数据库的其他部分链接用户进行的交易,如下所示:

transactionsPerUser {
     user1 {
           order.$key (key generated by push) : "true"
                     }
            {

如您所见,我正在尝试 console.log(order.$key) 但它返回未定义。我该如何解决这个问题?其次,这是构建我的数据库的正确方法吗?感谢您的帮助!

【问题讨论】:

    标签: javascript angular firebase firebase-realtime-database angularfire2


    【解决方案1】:

    我会对 post 行做一个小改动,并在交易中添加 /

    postData(order: orderInfo) {
        let uid = firebase.auth().currentUser.uid;
    
    // Change this next line to save the transaction
    
        var newRef = this.db.list('/transactions').push({
          currency: order.currency,
          total: order.total,
          rate: order.rate,
          uid: uid
        });
    
    // get just the key reference
    var newKey= newRef.key;
    
    //then change this refer
    
        console.log(newKey);
    
    //To update you would change the next line
    
        this.db.list('transactionsPerUser').update(newKey, order.newInfo);
    }
    

    【讨论】:

    • 然后要从列表中的对象中获取密钥,您可以调用 order.$key
    • 嗨,加文。谢谢你的帮助。我现在在控制台中收到此错误 Firebase.update 失败:“第一个参数必须是包含要替换的子项的对象。”
    • 这是我对字段进行更新的方式,请注意 name 是字段的类型,您需要先给 name 一个值 if(this.order.name){ this.db.list ('transactionsPerUser').update(newKey, {name : this.name }); }
    • 由于您来自 2 个不同的列表,请不要忘记确保您获得正确列表的正确关键参考
    • 您错过了一些步骤,但它对我有帮助,所以我将您的答案标记为正确。这是缺少的var newKey= newRef.key; var keyTrans = {}; keyTrans[newKey] = true; console.log(newKey); this.db.list('transactionsPerUser').update(uid, keyTrans);
    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 2017-10-21
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    相关资源
    最近更新 更多