Toggle boolean field in Firestore using FieldValue

Viewed 37

I'm currently trying to create a toggle function for a Firestore boolean field. I would like to know if there is any way to toggle this boolean field directly via the .update() function, and avoid having to .get() that field's original value beforehand.

admin.firestore().collection('users').doc(uid).update({
    field: !field
});

I know Firebase's FieldValue actually helps avoiding that extra .get() call, and I thought FieldValue.isEqual() could maybe help me but what It does is comparing that field to another, not comparing itself to false, which is what I actually need:

admin.firestore().collection('users').doc(uid).update({
    field: admin.firestore.FieldValue.isEqual(false)
});
1 Answers

Since toggling the value means that you need to know the current value of the field, there is no way to do this in a single operation. Instead you will need to use a transaction to first read the document, and then write the modified field value back atomically.

Related