首页 > 解决方案 > 如果条件总是执行

问题描述

我正在尝试根据我的数据库中对象中的布尔值来调节 if 语句的执行。由于某种原因,它总是执行。我是 TypeScript 的新手,所以我可能会遇到一些基本错误。

这是我的代码:

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;
    };
});

我也尝试将它作为 if 语句(community.public === true),甚至只是这个(community.public)(因为值是布尔值)。但它总是执行。我在我的代码中找不到执行此函数的任何其他原因。我究竟做错了什么?

标签: node.jstypescriptfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


如果您想检查快照中是否有数据(总是在 onCreate 触发器中),然后检查其中的数据,这样会更好:

const community = snap.data();
if (community && community.public) {
    // your code
}

推荐阅读