mongodb findOneBy查不到数据返回为null

106 阅读1分钟

解决方式

1、存储数据对象

export class UserInfoListEntity {

/**

* 对象 ID

*/

@ObjectIdColumn()

id: ObjectId;

/**

* 用户Id

*/

avatar: string;

@Column()

phone: string;

}

这里存储的主键ObjectIdColumn为id 类型为ObjectId

2、数据库注入

constructor(private readonly userInfoRepo: MongoRepository)

3、调用

 const user = await this.userInfoRepo.findOneBy({

id: new ObjectId(data?.data?.user?.id + '12345'),

});

注意!! 这里ObjectId必须要是从mongodb引入的 不要按提示引入type类的 

--import { ObjectId } from 'mongodb';

且 调用的时候 必须要哟个new ObjectId包一层才能查找出来

4、错误提示Argument passed in must be a string of 12 bytes or a string of 24 hex charac

这里提示的意思是传入的参数必须是12字节的字符串或24十六进制字符的字符串

我的解决方案是把id凑24位的字符串 有大佬有更好的方式提醒下哈