0

I am trying to condition the execution of an if statement based on a Boolean value in an object in my DB. For some reason it always executes. I am new to TypeScript so I might be getting something basic wrong.

This is my code:

exports.newCommunity = functions.firestore.document('communities/{communityID}').onCreate((snap, context) => {

    const community = snap.data();
    if (community !== undefined) {
        if (community.public == true) {
            return createCommunityInAlgolia(community);
        } else {
            return null;
        };
    } else {
        return null;
    };
});

I tried also having this as the if statement (community.public === true) or even simply this (community.public) (as the value is a Boolean). But it always executes. I can't find any other reason in my code for this function to execute. What am I doing wrong?

Tsabary
  • 3,119
  • 2
  • 24
  • 66
  • What are the possible return values for `snap.data()`? – Jordi Nebot Aug 08 '19 at 09:18
  • Code looks correct. Looks like the problem in the data `community.public` (is always true) – Ihor Sakailiuk Aug 08 '19 at 09:23
  • maybe you're storing `community.public` as `string` representation of boolean values (e.g. "true", "false") – Ihor Sakailiuk Aug 08 '19 at 09:24
  • Please post possible values of `community` or just `community.public` – Ihor Sakailiuk Aug 08 '19 at 09:25
  • @JordiNebot `snap.data()` is always just documentData which is a map, or null. But I made the check first so I know it's not null, plus the following function uses that data with no problem so the data must be alright – Tsabary Aug 08 '19 at 09:57
  • @IhorSakaylyuk I can see in the DB it is false. But I agree it looks like this would be the problem but it's not I tried to do `if (community.public as Boolean)` but that doesn't work either. – Tsabary Aug 08 '19 at 09:58
  • Maybe you have your false in the DB as a string and not as a boolean. Keep in mind that `'false'` is a truthy value. Take a look at [How can I convert a string to boolean in JavaScript?](https://stackoverflow.com/questions/263965/how-can-i-convert-a-string-to-boolean-in-javascript) – Jordi Nebot Aug 08 '19 at 10:17
  • Please add `console.log(typeof community.public)` and paste here what is the result – Ihor Sakailiuk Aug 08 '19 at 10:39

1 Answers1

1

If you want to check if there is data in the snapshot (which there will always be in an onCreate trigger), then check data inside that, this is better:

const community = snap.data();
if (community && community.public) {
    // your code
}
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441