user1354934
user1354934

Reputation: 8841

Firestore reference fields - should it not exist if there is no reference?

I am building an app where users have a currentActivity field that references an Activity.

ex:

User
  name: My Name
  currentActivity: activities/g07JPaTfuqSXgRG7tqVs

However, once the user is no longer doing that activity, should I remove that field from the User object, or is there a way to set it to NULL?

Upvotes: 0

Views: 43

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83153

You can choose to either:

  • Totally delete the field, or;
  • Set the field to null, or;
  • Set the field to another value like an empty string.

The last two cases have an advantage over the first one: you can query it with the not equal (!=) operator to return documents where the currentActivity field exists and does not match null or does not match the empty string (in other words the users with an activity).

You cannot do the same query with the first approach (field deletion) because you cannot query on a field that does not exists.

Note that the doc on the not equal operator in queries indicates that "you cannot use the not equal (!=) operator with null because x != null evaluates to undefined" but actually usersRef.where('currentActivity', '!=', null).get(); does work correctly: you get all the docs with a currentActivity field that is different of null.

More details in the following other Firestore documentation sections:

Upvotes: 1

Related Questions