【问题标题】:Setting custom key when pushing new data to firebase database将新数据推送到 Firebase 数据库时设置自定义键
【发布时间】:2023-03-04 09:54:01
【问题描述】:

好吧,我是 Firebase 的新手,我希望在将新数据推送到数据库时拥有自己的密钥。

问题:

FireBase.push().setValue(mapped_values);

这给出了如下结构:

如何在那里创建自己的自定义密钥? 比如用户名什么的。

【问题讨论】:

    标签: java android firebase firebase-realtime-database fire-sharp


    【解决方案1】:

    拨打push() 将为您生成一个密钥。

    如果您改用child(),您可以自己确定它们的键/路径。

    ref.child("Victor").setValue("setting custom key when pushing new data to firebase database");
    

    【讨论】:

    • 他没有将其标记为答案,因为它没有回答他的问题,因为无论您将什么推送或设置到数据库中,Firebase 都会自动生成一个带有随机密钥的孩子。
    • @FrenchyNYC 如果您使用.child('customkey')...则不是
    • 以及如何用 angularfire2 做到这一点?
    • @trojan 在构造函数中设置:constructor(private db: AngularFireDatabase) 你可以这样做:this.db.database.ref().child('somechild').set('somevalue')
    • 2020年应使用set()代替setValue()
    【解决方案2】:
            String key="1234567sdfsf8";
            //custom object
            User user=new User();
            DatabaseReference mDatabase;
            mDatabase = FirebaseDatabase.getInstance().getReference();
            mDatabase.child("Users").child(key).setValue(user);
    

    【讨论】:

    • 如果key key 不存在则抛出错误,因为setValue 没有定义
    【解决方案3】:

    作为对最佳答案的更新,Firebase API has been changedsetValue() 不再起作用。现在您必须改用set() 函数:

    ref.child("Victor").set("setting custom key when pushing new data to firebase database");
    

    【讨论】:

      【解决方案4】:

      您可以使用 setValue() 创建自定义键,即使根目录包含许多子项 例如,如果 'Users' 是 root 并且您想添加以电子邮件为键的用户,它将是这样的

      firebase.child("firebase url").child("Users").child("user_1 email").setValue(...)
      
      firebase.child("firebase url").child("Users").child("user_2 email").setValue(...)
      

      【讨论】:

        【解决方案5】:

        假设你的数据库看起来像

         "BookShelf" : {
            "book1" : {
              "bookName" : "book1_push"
               ...
             }
        

        你的代码是(不要使用push(),push()生成随机密钥)

        DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
        Book data = new Book();
        mDatabase.child("BookShelf").child("book1").setValue(data);
            
             
        

        【讨论】:

          【解决方案6】:

          如果您使用的是FirebaseUI

          private static final CollectionReference usersCollection = FirebaseFirestore.getInstance().collection("users");
          
          User user = new User("MyUsername", "MyPictureUrl");
          String userKey = "1234567sdfsf8";
          
          usersCollection.document(userKey).set(user); //MAGIC LINE
          

          【讨论】:

            【解决方案7】:

            只是为了分享知识。

            如果您使用的是 fire-sharp,您可以按如下方式创建自定义密钥

                        IFirebaseConfig config = new FirebaseConfig
                        {
                            AuthSecret = "SecretKey",
                            BasePath = "https://abc.firebaseio.com/",
                            Host = "abc.firebaseio.com/"
                        };
                        IFirebaseClient client = new FirebaseClient(config);
            
                        var obj = new Users
                        {
                            FirstName = "test",
                            MiddleName = "user",
                            LastName = "xyz"
            
                        };
            
                        SetResponse response = client.SetAsync("Profile", "YourID");//you can use Set() as well
                        response = client.SetAsync("Profile/YourID", obj);//you can use Set() as well
            

            【讨论】:

              【解决方案8】:

              简单快速

               Map<String,Object> taskMap = new HashMap<>();
                     taskMap.put("Name", name.getText().toString());
                     taskMap.put("km", km.getText().toString());
                    // taskMap.put("age", "45");
                     taskMap.put("Day", day.getText().toString());
                     mDatabaseReference.push().setValue(taskMap);
              

              【讨论】:

                【解决方案9】:

                如果数据库引用子是固定字符串,则不会添加新值。只是它会更新以前的值。例如:

                DatabaseReference myRef = FirebaseDatabase.getInstance().getReference(); String mText = // get data from editText or set your own custom data

                现在如果我插入这样的数据:

                myRef.child("abc").child("cba").setValue(mText);

                每次我插入数据时,它都会更新我以前的数据。它不会添加新数据。因为我的参考在这里是固定的(myRef.child("abc").child("cba") // 这个,总是固定的)。

                现在将子“cba”的值更改为无法修复的随机或动态值。例如:

                Random rand = new Random(); // Obtain a number between [0 - 49]. int n = rand.nextInt(50); myRef.child("abc").child(String.valueOf(n)).setValue(mText);

                在这种情况下,它将添加一个新值而不是更新。因为这个时间参考在这里不固定。它是动态的。 push() 方法完全相同。它生成随机密钥以保持唯一引用。

                【讨论】:

                  【解决方案10】:

                  在 POST 请求中它会生成 ID,但在 PATCH、PUT 请求中它会提及您将提供的密钥。

                  【讨论】:

                    【解决方案11】:

                    如果您使用 Node.js 写入 firebase 实时数据库,这里有一个函数:

                    function registerVibinScores( reference, childId, dataToWrite){
                    
                        var ref = db.ref(reference); //vibinScores
                        usersRef = ref.child(childId);
                        usersRef.set(
                            dataToWrite
                        );
                    
                    }
                    
                    //Example to invoke it:
                    var vibinEntry = {
                        "viberId": "425904090208534528",
                        "person": {
                            "name": "kukur",
                            "score": 0,
                            "id": "425904090208534528"
                        },
                        "vibinScore": 0,
                        "timeOfEntry": "2021-04-19T16:59:23.077Z"
                    }
                    
                    registerVibinScores('vibinScores/allEntries', 112, vibinEntry);
                    

                    The sample entry in your database would look like this

                    【讨论】:

                      猜你喜欢
                      • 2019-12-15
                      • 2020-07-08
                      • 2018-04-08
                      • 2021-08-28
                      • 2013-08-05
                      • 1970-01-01
                      • 1970-01-01
                      • 2021-10-07
                      • 2023-03-06
                      相关资源
                      最近更新 更多