Remove many relationships in firebase cloud firestore

684 Views Asked by At

I execute the following batch:

batch.set(doc, {
   "Users": {
      [userKey]: null
   }
}, { merge: true })

It places the null value for the relationship but does not delete it.

I need to delete the field and value of the object as it does in realtime database and not to be kept with a null value.

If I use firebase.firestore.FieldValue.delete() only works with the object and not with its fields.

1

There are 1 best solutions below

5
Gil Gilbert On

For better or worse, Firestore treats the null value as distinct from a field not existing, so setting a value to null won't do what you want.

FieldValue.delete() the way to delete fields, not documents, so this should delete the field:

batch.set(doc, {
  "Users": {
    [userKey]: firebase.firestore.FieldValue.delete()
  }
}, { merge: true });

However there's currently a bug in the released SDK that prevents this from working as intended. For now use

batch.update(
    'Users.userKey',
    firebase.firestore.FieldValue.delete());