2

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

 "users" : {
       "5yty2c8TyChQu3fMJ1O3d44wuq2" : {
       "Email" : "[email protected]",
       "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.

1 Answer 1

5

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});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.