2

I would like to find a user by their phone number and update their displayName in Firebase Cloud Functions using the Admin SDK. When I try to run this code for example:

import * as admin from 'firebase-admin'
admin.auth().getUserByPhoneNumber(phone).then((user) => {
   user.displayName = newName;
}).catch((reason) => console.log(reason['message']));

I get the following message:

Cannot assign to read only property 'displayName' of object '#UserRecord'

Although I undestand this exception, I cannot think of a diffrent way to do this. Any idea?

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Oval
  • 37
  • 8

1 Answers1

7

The getUserByPhoneNumber() method returns a UserRecord which doesn't have any method to modify the user object.

You need to use the updateUser() method to do so, as follows:

//....
return admin.auth().getUserByPhoneNumber(phone)
.then(userRecord => {
   return admin.auth().updateUser(userRecord.uid, {displayName: newName});
})
.catch((reason) => console.log(reason['message']));

Don't forget to return the Promise chain if your Cloud Function is a background-triggered one, see https://firebase.google.com/docs/functions/terminate-functions

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121