简体   繁体   中英

React-Native Firebase update column

In Firebase database, I am trying to update one column only. Firebase database 'users' JSON:

 "users" : {
       "5yty2c8TyChQu3fMJ1O3d44wuq2" : {
       "Email" : "myEmail@yahoo.com",
       "FirstName" : "John",
       "LastName" : "Smith",
       "MobileNumber" : "",
       "NickName" : "",
       "profile_picture" : ""
  }

I would like to update just one column - MobileNumber with this code:

   updateMobileNumber(){

    var updateData = {
                    MobileNumber: this.state.mobileNumber
                      };

    var updates = {};
    updates['/users/' + userId ] = updateData;

    database.ref('users/' + userId).update(updates);

    alert('Account Updated');

   }

The above code instead of updating MobileNumber column, it is removing all the other columns and adding Email column. What am I doing wrong ? I want to update Email column without touching other columns. Appreciate any help.

When you use

updates['/users/' + userId ] = updateData;

you're actually setting the value of users/userId into updateData, which is only 1 field. What you want to use is the method update that allow you to selectively update each field. Like this:

var adaNameRef = firebase.database().ref('users/ada/name');
// Modify the 'first' and 'last' properties, but leave other data at
// adaNameRef unchanged.
adaNameRef.update({ first: 'Ada', last: 'Lovelace' });

Here is the doc to the method: https://firebase.google.com/docs/reference/js/firebase.database.Reference#update

Also your code can simply be like this:

database.ref('users/' + userId).update({MobileNumber: newNumber});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM