【问题标题】:Typeorm, MongoDB and where operatorTypeorm、MongoDB 和 where 运算符
【发布时间】:2021-03-10 05:45:22
【问题描述】:

[带有 MongoDB 类型的 TypeORM]。您好,我有用户数据库,其中每个用户都有一个电子邮件道具,现在我想查找电子邮件以“test”开头的所有用户,例如返回值应该是 User[{email: 'test1'}, {email:' test2'}, ...] 但我无法在此处提取这些实体我如何进行查询:

 const users = await this.usersRepository.find({
    where: `"email" LIKE 'test%'`,
 });

但此代码返回整个用户集合。我也尝试过:

我也尝试过:

    const users = await this.usersRepository.find({
        where: {
            email: Like('test')
        }
    });

这个返回空数组[]

即使我尝试完全匹配,例如 Like('test21@abv.bg'),仍然返回空数组

如何让所有用户使用以“测试”开头的电子邮件提前谢谢!

【问题讨论】:

    标签: node.js mongodb express nestjs typeorm


    【解决方案1】:

    对于 MongoDB 使用正则表达式

    const users = await this.usersRepository.find({
        where: {
            email: new RegExp(`^${userEmail}`);
        }
    });
    

    【讨论】:

    • 返回空数组
    • @AndonMitev 看起来很奇怪。尝试运行原始 SQL SELECT * FROM "users" WHERE "email" LIKE 'test%' 以仔细检查您的数据是否存在问题
    • 我会尝试将您的条件直接作为查找方法参数,例如 .find({ email: Like('test%') });但我想这不会有任何区别。参考:github.com/typeorm/typeorm/blob/master/docs/…
    • 是的,我使用 MongoDB 和 TypeORM 没有区别
    • @AndonMitev 它改变了一切。您需要在您的情况下使用正则表达式 { email: /^test/ }
    猜你喜欢
    • 2021-12-03
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    • 2019-11-02
    • 2021-11-13
    • 2012-05-21
    • 2021-10-06
    相关资源
    最近更新 更多