检查 javascript 中的 undefined 或 null

checking undefined or null in javascript

我在 nestjs.

中有以下方法
async findOne(userId: string) {
        const user = await this.userRepository.find({userId});
        if (user) {
            throw new NotFoundException(`User does not exist`);
        }
        return user;
        
    }

此方法返回 array of object。如果在数据库中找不到值,则它 return [{}]。 当 return empty array 我的意思是 [{}] 时,我需要抛出异常。为此,我需要将 condition 放在 if 块中 当我在 if 块中写入 user、或 user==nulluser.length==o 时,在所有情况下它都不会进入 if

我需要在 if 块中做哪些修改?

您似乎需要检查 user 是否是长度为 1 的数组,其中第一个元素是空对象。你可以这样做:

const user = await this.userRepository.find({ userId });
if (
  !user ||
  user.length === 0 ||
  (user.length === 1 && Object.keys(user[0]).length === 0)
) {
  throw new NotFoundException(`User does not exist`);
}
return user;

您需要查看 userRepositoy.find() 函数,看看是否有任何其他可能的值 return。根据您的描述,它要么是 return 一个用户数组,要么是一个包含单个空对象的数组。但是,可能还有其他失败案例 return 有所不同。这部分取决于您,以确保您正确处理这些情况。

我想知道为什么您实际上需要使用 find 方法。

您正在尝试根据 usersRepository 中的 userId 获取用户,userId 不应该是唯一的吗?

如果它是唯一的,那么您得到的要么是您所描述的空数组,要么其中只有一个对象。不确定您使用的是什么数据库,但无论如何,应该有 findOne 方法。

如果这适用于您的情况 findOne 应该可以解决问题

const user = await this.userRepository.findOne({ userId });
if (!user) throw new NotFoundException(`User does not exist`);

return user;

或者如果你必须使用 find 并且你想让 if 语句更具可读性,我建议使用 Ramda, lodash 或任何类似的库来保持它的清洁。

使用 Ramda,您可以执行以下操作

const [firstUser = {}, ...others] = await this.userRepository.find({ userId });
if(R.isEmpty(firstUser)) throw new NotFoundException(`User does not exist`);

return [firstUser, ...others];

我高度假设基于userId获取的数据只是一条记录所以我相信你可以像这样使用

const [user = {}] = await this.userRepository.find({ userId });
if(R.isEmpty(user)) throw new NotFoundException(`User does not exist`);

return user;