我想检查数据是否已存在于我的数据库中> 按照代码:
Entity
@Column('simple-array')
users: string[];
我的数据库中的以下数据为
{
id: '57b41c65-ae8d-4cf0-8246-a85f296cf1ce',
createdAt: 2023-10-14T10:07:44.386Z,
updatedAt: 2023-10-14T10:07:44.386Z,
deletedAt: null,
users: [
'888ce1ad-8ee4-4518-977a-78b66275ee9d',
'529938d1-33fd-4aa1-bd2a-9eb741b5c19f'
]
}
如果我想知道数据是否已经存在于我的表中
public async testData(
firstUserId: string,
body: AddConversationDto,
): {
const { userId } = body;
const conversation = await this.chatConversationRepositoryService.findMany({
users: In[userId],
});
if (conversation)
return { message: this.i18nService.t('systemMessage.addConversation') };
await this.chatConversationRepositoryService.save({
users: [firstUserId, userId],
});
return { message: this.i18nService.t('systemMessage.addConversation') };
} 我已多次尝试查找是否已经存在,但它不起作用。它仅显示所有数据。
首先要注意的是,您使用的是
simple-array
类型。当您获取数据时,TypeORM 将其表示为数组;但是,在数据库中,它不保存为数组。它是一个用逗号分隔的常规字符串。
文档指出:
请注意,您写入的值中不得有任何逗号。
当你有一个清单时
const A = ['a', 'b', 'c'];
它将另存为:
"a,b,c"
确保您没有使用可能包含逗号的数据,或者至少在保存之前清理它们。
最终它是一个字符串,这意味着你需要字符串函数来判断它是否存在。
LIKE
,例如。
我注意到的另一个问题是您正在使用
findMany
函数。如果你想确定某个东西是否存在,findMany
不是你所需要的。该函数始终返回一个数组作为响应。如果没有匹配,它将是一个空列表,这意味着您的 if 语句 if (conversation){}
将始终是 true
,因为空数组需要通过其长度进行检查,例如if(list.length > 0){}
长话短说,如果目标是只找到一个匹配项,则使用
findOne
代替。与 null
不同,它将给出记录或 findMany
值。
但是,就您的情况而言,您可以使用
exists
方法进行杠杆作用,如下所示:
const conversation = await this.chatConversationRepositoryService.exist({
where: {
users: Like(`%${userId}%`)
}
});
这将返回一个布尔值。
附注
在此处发布时,请确保正确格式化代码并消除所有不相关的内容。这样您就可以增加在此平台上获得帮助的机会。