先创建一条数据 数据库里面已经有了。
模糊查询代码
async findAll({ page, pageSize, params }: PaginationParamsDto) {
const { name, phone, email } = params;
const query: MongoFindManyOptions<User> = {
order: {
updatedDate: 'DESC',
},
skip: (page - 1) * pageSize,
take: pageSize * 1,
cache: true,
where: {
...(name ? { name: Like(`%${name}%`) } : {}),
...(phone ? { phone: Like(`%${phone}%`) } : {}),
...(email ? { email: Like(`%${email}%`) } : {}),
},
};
console.log('query', query);
const [data, count] = await this.userRepository.findAndCount(query);
return {
code: 200,
data,
count,
};
}
使用到了。Like。
咦。查询不到数据。
呜呜。。。。。。。
然后各种百度搜索
看到了这个
ok 改造代码 最后如下
// 模糊查询 分页接口
async findAll({ page, pageSize, params }: PaginationParamsDto) {
const { name, phone, email } = params;
const query: MongoFindManyOptions<User> = {
order: {
updatedDate: 'DESC',
},
skip: (page - 1) * pageSize,
take: pageSize * 1,
cache: true,
where: {
// TODO 模糊查询无效,Like不行?。需要使用正则表达式
...(name ? { name: new RegExp(`${name}`) } : {}),
...(phone ? { phone: new RegExp(`${phone}`) } : {}),
...(email ? { email: new RegExp(`${email}`) } : {}),
},
};
console.log('query', query);
const [data, count] = await this.userRepository.findAndCount(query);
return {
code: 200,
data,
count,
};
}
哈哈哈哈。查询到了数据。
npm 包如下:
"mongodb": "^5.2.0",
"typeorm": "^0.3.15",
不知道原因, 希望有个大神具体告知一下。官方文档也没有特殊说明、