【问题标题】:Nest.js TypeORM FindOneBy returns null even with data on the databaseNest.js TypeORM FindOneBy 即使有数据库上的数据也会返回 null
【发布时间】:2022-10-20 22:40:23
【问题描述】:

所以我有这个实体......

import { Column, Entity, PrimaryColumn } from "typeorm";

@Entity('Users')
export class User {
  @PrimaryColumn({ type: 'nvarchar', length: 36, unique: true })
  UserId: string;

  @Column({ type: 'nvarchar', length: 100, unique: true })
  Email: string;

  @Column({ type: 'nvarchar', length: 36 })
  CrmUserId: string;

  @Column({ type: 'nvarchar', length: 36, nullable: true })
  AzureB2CUserId: string;

  @Column({ type: 'bit', default: false })
  IsActive: boolean;

  @Column({ type: 'nvarchar', length: 100 })
  CreatedBy: string;

  @Column({ type: 'datetime' })
  CreatedDate: Date;

  @Column({ type: 'nvarchar', length: 100, nullable: true })
  UpdatedBy: string;

  @Column({ type: 'datetime', nullable: true })
  UpdatedDate: Date;
}

并使用 TypeORM 我想通过电子邮件获取一条记录,而不是 UserId。所以我在存储库中有这个。

public async getUserByEmail(email: string): Promise<User | null> {
  let _res = await this._userRepository.findOne({ where: { Email: email, IsActive: true }})
  return _res;
}

但它总是返回一个空值,即使记录存在,我也在考虑用 CreateQueryBuilder 来做,像这样......

public async getUserByEmail(email: string): Promise<User | null> {
    let _res = await this._userRepository.createQueryBuilder()
        .select()
        .from(User, "Users")
        .where('email = :emailParameter', { email })
        .getOne();
    return _res;
}

但结果是一样的,我不断地得到空值,我不知道我做错了什么,因为如果我在 findOne 和 findOneBy 上使用主键,它就可以工作。有什么帮助吗?

【问题讨论】:

  • 从您的createQueryBuilder() 中删除.select().from()
  • @micaelLevi 让它工作,谢谢

标签: nestjs typeorm


【解决方案1】:
  1. 如果您使用的是 MongoDB,请使用 import { MongoRepository, Repository } from 'typeorm'; 作为 _userRepository 类型。

  2. 使用 _userRepository findOneBy 时将 userId 参数包装在 import { ObjectId } from 'mongodb' const query = {"_id":ObjectId(req.params.productId)}

  3. OR have a look at this example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    相关资源
    最近更新 更多