I have a firestore collection called events
that contains documents with the fields begin
, end
and title
.
The function is triggered if a document was changed.
begin
and end
are of type timestamp
.
I want my function to return false
if begin
or end
was changed.
In my cloud function, I check if the respective before and after data is equal, however true
is returned, even though only the field title
was changed.
const before = change.before.data() const after = change.after.data() //begin and end weren't changed. Still, true is returned if (before?.begin == after?.begin && before?.end == after?.end) { return false } return true
When comparing the milliseconds, it works:
const before = change.before.data() const after = change.after.data() //begin and end weren't changed. false is returned if (before?.begin.toMillis() == after?.begin.toMillis() && before?.end.toMillis() == after?.end.toMillis()) { return false }
What causes this? Shouldn’t I be able to compare the Timestamp
objects itself instead of comparing it using a member function?
Advertisement
Answer
Shouldn’t I be able to compare the Timestamp objects itself instead of comparing it using a member function?
No, the ==
operator in JavaScript, when applied to objects, only compares the references to the two objects. It does not compare them deeply. So, it will only yield true if the two objects are the exact same object.
If you want to compare two Timestamp objects, you will need to compare them deeply. As you can see from the linked API documentation, there is a isEqual method provided on Timestamp that will do that for you.
before?.begin.isEqual(after?.begin)
When you used toMillis
, what you were doing was comparing two JavaScript number objects, which are compared by their actual values more intuitively. It is also not an exact comparison in this case, since Timestamp can represent nanosecond precision times. Conversion to milliseconds loses data.