Reputation: 258
I wanted to clarify how to update existing data in my Firebase Realtime Database.
- users
- 12313123
- isAuth: "True"
- didPay: "True"
- ...
So the user class looks like:
class User(
val isAuth: String,
val didPay: String
...
)
I already have 100x existing users. How can I add to my User
model class now one more property that would be automatically added to all users? Do I've to do change for "creating" new users + automatically run a function to update all existing users or is there a simpler way?
class User(
val userName: String,
val isAuth: String,
val didPay: String
...
)
Upvotes: 2
Views: 1347
Reputation: 138824
According to your last comment:
Normal scenario when your data class model changes (new parameters/fields are added) you would need migration (for local databases like room for instance) to make sure that users that use previous database versions do not crash. I'm asking how do I change existing user database fields so they do not run in NPE when I call the same code for users that do not have this type of field in the database yet (only newly created users would have new fields - what happens to old users?)
There are two solutions. The first one would be to always check the value of a property against null
. However, this might not solve the problem now, as I understand that older versions of your app don't do that.
The second solution is to update all properties within all documents with default data. In this way, there will be no way you can get a NullPointerException
, as all properties will hold values. When using a POJO class, please check my answer from the following post:
Otherwise, please use the following lines of code:
val rootRef = FirebaseFirestore.getInstance()
val usersRef = rootRef.collection("users")
usersRef.get().addOnCompleteListener { task ->
if (task.isSuccessful) {
for (document in task.result!!) {
document.reference.update(
"newFieldOne", "DataOne",
"newFieldTwo", "DataTwo"
)
}
}
}
And for Java users:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
usersRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
document.getReference().update(
"newFieldOne", "DataOne",
"newFieldTwo", "DataTwo"
);
}
}
}
});
Upvotes: 1