where 条件中 null 与 undefined 的处理
在 'WHERE' 条件中,null 和 undefined 这两个值在 TypeORM 里并不是严格合法的值。
传入一个已知的 null 值会在编译期被 TypeScript 禁止(当你在 tsconfig.json 中启用了 strictNullChecks 时)。默认行为是:运行时遇到的 null 与 undefined 值会抛出错误。
null 与 undefined 值的处理方式可以通过数据源选项中的 invalidWhereValuesBehavior 配置项自定义。它适用于查找操作、repository 方法以及 EntityManager 方法(update、delete、softDelete、restore)等高层操作。
该设置 不会 影响 QueryBuilder 的 .where()、.andWhere() 或 .orWhere() 方法。QueryBuilder 是底层 API,null/undefined 值会原样透传。在 QueryBuilder 中请使用 IsNull() 操作符或参数化条件来显式处理 null。
默认行为
默认情况下,当 where 条件中出现 null 或 undefined 值时,TypeORM 会抛出错误。这能避免意外结果,并帮助你尽早发现潜在 bug:
// 两条查询都会抛出错误
const posts1 = await repository.find({
where: {
text: null,
},
})
// Error: Null value encountered in property 'text' of a where condition.
const posts2 = await repository.find({
where: {
text: undefined,
},
})
// Error: Undefined value encountered in property 'text' of a where condition.要在 where 条件中匹配 null 值,请使用 IsNull 操作符(详见查找选项):
const posts = await repository.find({
where: {
text: IsNull(),
},
})配置
你可以在数据源配置中用 invalidWhereValuesBehavior 选项自定义 null 与 undefined 值的处理方式:
const dataSource = new DataSource({
// ... 其他选项
invalidWhereValuesBehavior: {
null: "ignore" | "sql-null" | "throw",
undefined: "ignore" | "throw",
},
})null 行为选项
null 的行为可以设为以下三个值之一:
'ignore'
where 条件中的 JavaScript null 值会被忽略,该属性被跳过:
const dataSource = new DataSource({
// ... 其他选项
invalidWhereValuesBehavior: {
null: "ignore",
},
})
// 这会返回所有帖子,忽略 text 属性
const posts = await repository.find({
where: {
text: null,
},
})'sql-null'
JavaScript 的 null 值会被转换为 SQL 的 NULL 条件:
const dataSource = new DataSource({
// ... 其他选项
invalidWhereValuesBehavior: {
null: "sql-null",
},
})
// 这只会返回数据库中 text 列为 NULL 的帖子
const posts = await repository.find({
where: {
text: null,
},
})'throw'(默认)
JavaScript 的 null 值会导致抛出 TypeORMError:
const dataSource = new DataSource({
// ... 其他选项
invalidWhereValuesBehavior: {
null: "throw",
},
})
// 这会抛出错误
const posts = await repository.find({
where: {
text: null,
},
})
// Error: Null value encountered in property 'text' of a where condition.
// To match with SQL NULL, the IsNull() operator must be used.
// Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in data source options to skip or handle null values.undefined 行为选项
undefined 的行为可以设为以下两个值之一:
'ignore'
where 条件中的 JavaScript undefined 值会被忽略,该属性被跳过:
const dataSource = new DataSource({
// ... 其他选项
invalidWhereValuesBehavior: {
undefined: "ignore",
},
})
// 这会返回所有帖子,忽略 text 属性
const posts = await repository.find({
where: {
text: undefined,
},
})'throw'(默认)
JavaScript 的 undefined 值会导致抛出 TypeORMError:
const dataSource = new DataSource({
// ... 其他选项
invalidWhereValuesBehavior: {
undefined: "throw",
},
})
// 这会抛出错误
const posts = await repository.find({
where: {
text: undefined,
},
})
// Error: Undefined value encountered in property 'text' of a where condition.
// Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in data source options to skip properties with undefined values.注意,这只适用于被显式设置为 undefined 的值,不适用于被省略的属性。
同时使用两个选项
你可以分别配置两种行为,以获得全面的控制:
const dataSource = new DataSource({
// ... 其他选项
invalidWhereValuesBehavior: {
null: "sql-null",
undefined: "throw",
},
})该配置会:
- 把 where 条件中的 JavaScript
null值转换为 SQLNULL - 一旦遇到任何
undefined值就抛出错误 - 仍然忽略 where 子句中未提供的属性
当你想要做到以下几点时,这种组合很有用:
- 明确地表达"在数据库中查找 NULL 值"
- 捕获那些 undefined 值可能悄悄混入查询的潜在编程错误
受支持的操作
invalidWhereValuesBehavior 配置适用于 TypeORM 的高层操作,不适用于 QueryBuilder 直接调用的 .where() 方法:
查找操作
// Repository.find() / findOne() / findBy() / findOneBy()
await repository.find({ where: { text: null } }) // 遵循 invalidWhereValuesBehavior
// EntityManager.find() / findOne() / findBy() / findOneBy()
await manager.find(Post, { where: { text: null } }) // 遵循 invalidWhereValuesBehaviorRepository 与 EntityManager 方法
// Repository.update()
await repository.update({ text: null }, { title: "Updated" }) // 遵循 invalidWhereValuesBehavior
// Repository.delete()
await repository.delete({ text: null }) // 遵循 invalidWhereValuesBehavior
// EntityManager.update()
await manager.update(Post, { text: null }, { title: "Updated" }) // 遵循 invalidWhereValuesBehavior
// EntityManager.delete()
await manager.delete(Post, { text: null }) // 遵循 invalidWhereValuesBehavior
// EntityManager.softDelete()
await manager.softDelete(Post, { text: null }) // 遵循 invalidWhereValuesBehavior空条件会被拒绝。 update、delete、softDelete 和 restore 要求条件非空——空条件会渲染成 WHERE 1=1 并影响 每一 行。由于 "ignore" 会剥离值为 null/undefined 的属性,一个所有键都被剥离的条件就会变成空条件。此时该操作会被拒绝,而不是作为无过滤的写操作执行:
const dataSource = new DataSource({
// ... 其他选项
invalidWhereValuesBehavior: { null: "ignore", undefined: "ignore" },
})
// { text: null } 剥离后变成 {} -> 被拒绝;表不会被清空
await manager.delete(Post, { text: null })
// Error: Empty criteria(s) are not allowed for the delete method.当你确实想影响每一行时,请使用专门的 updateAll() / deleteAll() 方法。
只有普通对象条件会被规范化
invalidWhereValuesBehavior 只规范化普通的 FindOptionsWhere 对象。传给 update / delete / softDelete / restore 的任何其他条件值——实体类实例、FindOperator、数组、Date、Buffer,或原始类型的 id——都会原样透传,不会被校验。因此,一个可空列为 null 的实体实例会渲染成 col = NULL(匹配不到任何行),而不是抛出错误或被转换。如果你需要 null 处理,请传入一个带 IsNull() 操作符的普通对象(例如 { text: IsNull() })。
对实体实例条件做深度校验需要实体元数据,不在此处讨论范围内;当你希望
invalidWhereValuesBehavior生效时,请使用普通的FindOptionsWhere对象。
配合 setFindOptions 的 QueryBuilder
// setFindOptions 走的是查找选项路径,因此遵循该设置
await dataSource
.createQueryBuilder(Post, "post")
.setFindOptions({ where: { text: null } }) // 遵循 invalidWhereValuesBehavior
.getMany()不受影响:QueryBuilder 的 .where()
QueryBuilder 的 .where()、.andWhere() 和 .orWhere() 是底层 API,不受该设置影响。null 与 undefined 值会原样透传:
// 这不遵循 invalidWhereValuesBehavior —— null 原样透传
await dataSource
.createQueryBuilder()
.update(Post)
.set({ title: "Updated" })
.where({ text: null })
.execute()null 与 undefined 在 QueryBuilder .where() 中的行为
由于 QueryBuilder 是底层 API,null 与 undefined 值 不会 被校验或转换。理解它们的行为对避免意外结果很重要。
QueryBuilder .where() 中的 null
当在对象风格的 .where() 中把 null 作为值传入时,它会生成一个针对 NULL 的 SQL 等值判断:
await dataSource
.createQueryBuilder(Post, "post")
.where({ text: null })
.getMany()
// 生成:WHERE post.text = NULL在 SQL 中,column = NULL 永远为假 ——没有任何值等于 NULL。这条查询会 返回零条结果,这几乎肯定不是你的本意。要匹配 NULL 值,请使用 IsNull() 操作符:
import { IsNull } from "typeorm"
await dataSource
.createQueryBuilder(Post, "post")
.where({ text: IsNull() })
.getMany()
// 生成:WHERE post.text IS NULL或者使用字符串条件:
await dataSource
.createQueryBuilder(Post, "post")
.where("post.text IS NULL")
.getMany()QueryBuilder .where() 中的 undefined
当把 undefined 作为值传入时,行为相同——它会生成 WHERE column = NULL,永远为假:
await dataSource
.createQueryBuilder(Post, "post")
.where({ text: undefined })
.getMany()
// 生成:WHERE post.text = NULL
// 返回:零条结果汇总表
| 值 | 高层 API(find/repository/manager) | QueryBuilder .where() |
|---|---|---|
null 配 "ignore" |
属性被跳过——不加过滤 | WHERE col = NULL——零条结果 |
null 配 "sql-null" |
WHERE col IS NULL |
WHERE col = NULL——零条结果 |
null 配 "throw"(默认) |
抛出错误 | WHERE col = NULL——零条结果 |
undefined 配 "ignore" |
属性被跳过——不加过滤 | WHERE col = NULL——零条结果 |
undefined 配 "throw"(默认) |
抛出错误 | WHERE col = NULL——零条结果 |
IsNull() |
WHERE col IS NULL |
WHERE col IS NULL |
无论使用哪个 API,只要你想匹配 SQL 的 NULL 值,就始终使用 IsNull()。它在高层 API 和 QueryBuilder 上下文中都能正确工作。
In 'WHERE' conditions the values null and undefined are not strictly valid values in TypeORM.
Passing a known null value is disallowed by TypeScript (when you've enabled strictNullChecks in tsconfig.json) at compile time. The default behavior is for null and undefined values encountered at runtime to throw an error.
The way in which null and undefined values are handled can be customised through the invalidWhereValuesBehavior configuration option in your data source options. This applies to high-level operations such as find operations, repository methods, and EntityManager methods (update, delete, softDelete, restore).
This setting does not affect QueryBuilder's .where(), .andWhere(), or .orWhere() methods. QueryBuilder is a low-level API where null/undefined values pass through as-is. Use the IsNull() operator or parameterized conditions in QueryBuilder for explicit null handling.
Default Behavior
By default, TypeORM throws an error when null or undefined values are encountered in where conditions. This prevents unexpected results and helps catch potential bugs early:
// Both queries will throw an error
const posts1 = await repository.find({
where: {
text: null,
},
})
// Error: Null value encountered in property 'text' of a where condition.
const posts2 = await repository.find({
where: {
text: undefined,
},
})
// Error: Undefined value encountered in property 'text' of a where condition.To match null values in where conditions, use the IsNull operator (for details see Find Options):
const posts = await repository.find({
where: {
text: IsNull(),
},
})Configuration
You can customize how null and undefined values are handled using the invalidWhereValuesBehavior option in your data source configuration:
const dataSource = new DataSource({
// ... other options
invalidWhereValuesBehavior: {
null: "ignore" | "sql-null" | "throw",
undefined: "ignore" | "throw",
},
})Null Behavior Options
The null behavior can be set to one of three values:
'ignore'
JavaScript null values in where conditions are ignored and the property is skipped:
const dataSource = new DataSource({
// ... other options
invalidWhereValuesBehavior: {
null: "ignore",
},
})
// This will return all posts, ignoring the text property
const posts = await repository.find({
where: {
text: null,
},
})'sql-null'
JavaScript null values are transformed into SQL NULL conditions:
const dataSource = new DataSource({
// ... other options
invalidWhereValuesBehavior: {
null: "sql-null",
},
})
// This will only return posts where the text column is NULL in the database
const posts = await repository.find({
where: {
text: null,
},
})'throw' (default)
JavaScript null values cause a TypeORMError to be thrown:
const dataSource = new DataSource({
// ... other options
invalidWhereValuesBehavior: {
null: "throw",
},
})
// This will throw an error
const posts = await repository.find({
where: {
text: null,
},
})
// Error: Null value encountered in property 'text' of a where condition.
// To match with SQL NULL, the IsNull() operator must be used.
// Set 'invalidWhereValuesBehavior.null' to 'ignore' or 'sql-null' in data source options to skip or handle null values.Undefined Behavior Options
The undefined behavior can be set to one of two values:
'ignore'
JavaScript undefined values in where conditions are ignored and the property is skipped:
const dataSource = new DataSource({
// ... other options
invalidWhereValuesBehavior: {
undefined: "ignore",
},
})
// This will return all posts, ignoring the text property
const posts = await repository.find({
where: {
text: undefined,
},
})'throw' (default)
JavaScript undefined values cause a TypeORMError to be thrown:
const dataSource = new DataSource({
// ... other options
invalidWhereValuesBehavior: {
undefined: "throw",
},
})
// This will throw an error
const posts = await repository.find({
where: {
text: undefined,
},
})
// Error: Undefined value encountered in property 'text' of a where condition.
// Set 'invalidWhereValuesBehavior.undefined' to 'ignore' in data source options to skip properties with undefined values.Note that this only applies to explicitly set undefined values, not omitted properties.
Using Both Options Together
You can configure both behaviors independently for comprehensive control:
const dataSource = new DataSource({
// ... other options
invalidWhereValuesBehavior: {
null: "sql-null",
undefined: "throw",
},
})This configuration will:
- Transform JavaScript
nullvalues to SQLNULLin where conditions - Throw an error if any
undefinedvalues are encountered - Still ignore properties that are not provided in the where clause
This combination is useful when you want to:
- Be explicit about searching for NULL values in the database
- Catch potential programming errors where undefined values might slip into your queries
Supported operations
The invalidWhereValuesBehavior configuration applies to high-level TypeORM operations, not QueryBuilder's direct .where() method:
Find Operations
// Repository.find() / findOne() / findBy() / findOneBy()
await repository.find({ where: { text: null } }) // Respects invalidWhereValuesBehavior
// EntityManager.find() / findOne() / findBy() / findOneBy()
await manager.find(Post, { where: { text: null } }) // Respects invalidWhereValuesBehaviorRepository and EntityManager Methods
// Repository.update()
await repository.update({ text: null }, { title: "Updated" }) // Respects invalidWhereValuesBehavior
// Repository.delete()
await repository.delete({ text: null }) // Respects invalidWhereValuesBehavior
// EntityManager.update()
await manager.update(Post, { text: null }, { title: "Updated" }) // Respects invalidWhereValuesBehavior
// EntityManager.delete()
await manager.delete(Post, { text: null }) // Respects invalidWhereValuesBehavior
// EntityManager.softDelete()
await manager.softDelete(Post, { text: null }) // Respects invalidWhereValuesBehaviorEmpty criteria are rejected. update, delete, softDelete, and restore require non-empty criteria — an empty condition would render as WHERE 1=1 and affect every row. Because "ignore" strips null/undefined properties, a criteria whose keys are all stripped becomes empty. In that case the operation is rejected instead of running as an unfiltered write:
const dataSource = new DataSource({
// ... other options
invalidWhereValuesBehavior: { null: "ignore", undefined: "ignore" },
})
// { text: null } becomes {} after stripping -> rejected; the table is NOT emptied
await manager.delete(Post, { text: null })
// Error: Empty criteria(s) are not allowed for the delete method.Use the dedicated updateAll() / deleteAll() methods when you intentionally want to affect every row.
Only plain-object criteria is normalized
invalidWhereValuesBehavior normalizes plain FindOptionsWhere objects only. Any other criteria value passed to update / delete / softDelete / restore — an entity class instance, a FindOperator, an array, a Date, a Buffer, or a primitive id — is passed through untouched and is not validated. So an entity instance whose nullable column is null renders as col = NULL (matching nothing), rather than throwing/converting. If you need null handling, pass a plain object with the IsNull() operator (e.g. { text: IsNull() }).
Deep validation of entity-instance criteria requires entity metadata and is out of scope here; use a plain
FindOptionsWhereobject when you wantinvalidWhereValuesBehaviorapplied.
QueryBuilder with setFindOptions
// setFindOptions goes through the find-options path, so it respects the setting
await dataSource
.createQueryBuilder(Post, "post")
.setFindOptions({ where: { text: null } }) // Respects invalidWhereValuesBehavior
.getMany()Not affected: QueryBuilder .where()
QueryBuilder's .where(), .andWhere(), and .orWhere() are low-level APIs and are not affected by this setting. Null and undefined values pass through as-is:
// This does NOT respect invalidWhereValuesBehavior — null passes through as-is
await dataSource
.createQueryBuilder()
.update(Post)
.set({ title: "Updated" })
.where({ text: null })
.execute()How null and undefined behave in QueryBuilder .where()
Since QueryBuilder is a low-level API, null and undefined values are not validated or transformed. Understanding their behavior is important to avoid unexpected results.
null in QueryBuilder .where()
When null is passed as a value in an object-style .where(), it generates a SQL equality check against NULL:
await dataSource
.createQueryBuilder(Post, "post")
.where({ text: null })
.getMany()
// Generates: WHERE post.text = NULLIn SQL, column = NULL is always false — nothing equals NULL. This query will return zero results, which is almost certainly not what you intended. To match NULL values, use the IsNull() operator:
import { IsNull } from "typeorm"
await dataSource
.createQueryBuilder(Post, "post")
.where({ text: IsNull() })
.getMany()
// Generates: WHERE post.text IS NULLOr use a string condition:
await dataSource
.createQueryBuilder(Post, "post")
.where("post.text IS NULL")
.getMany()undefined in QueryBuilder .where()
When undefined is passed as a value, the same behavior applies — it generates WHERE column = NULL, which is always false:
await dataSource
.createQueryBuilder(Post, "post")
.where({ text: undefined })
.getMany()
// Generates: WHERE post.text = NULL
// Returns: zero resultsSummary table
| Value | High-level API (find/repository/manager) | QueryBuilder .where() |
|---|---|---|
null with "ignore" |
Property skipped — no filter | WHERE col = NULL — zero results |
null with "sql-null" |
WHERE col IS NULL |
WHERE col = NULL — zero results |
null with "throw" (default) |
Throws error | WHERE col = NULL — zero results |
undefined with "ignore" |
Property skipped — no filter | WHERE col = NULL — zero results |
undefined with "throw" (default) |
Throws error | WHERE col = NULL — zero results |
IsNull() |
WHERE col IS NULL |
WHERE col IS NULL |
Always use IsNull() when you want to match SQL NULL values, regardless of which API you use. It works correctly in both high-level and QueryBuilder contexts.