count
统计满足条件的实体数量。
方法签名
count(options: CountOptions<T>): Observable<number>
参数
interface CountOptions<T> {
where: RuleGroup<InstanceType<T>>;
}
示例
基础计数
import { firstValueFrom } from 'rxjs';
const total = await firstValueFrom(Todo.count({ where: { combinator: 'and', rules: [] } }));
条件计数
const completed = await firstValueFrom(
Todo.count({
where: {
combinator: 'and',
rules: [{ field: 'completed', operator: '=', value: true }]
}
})
);
搭配分页
async function getPagedTodos(page: number, pageSize: number) {
const where = { combinator: 'and' as const, rules: [] };
const [items, total] = await Promise.all([
firstValueFrom(
Todo.find({
where,
orderBy: [{ field: 'createdAt', sort: 'desc' }],
limit: pageSize,
offset: (page - 1) * pageSize
})
),
firstValueFrom(Todo.count({ where }))
]);
return { items, total, page, pageSize, totalPages: Math.ceil(total / pageSize) };
}
关系字段
const userTodoCount = await firstValueFrom(
Todo.count({
where: {
combinator: 'and',
rules: [{ field: 'owner.id', operator: '=', value: userId }]
}
})
);