如何解决MongoDB:如何避免集合中的名称翻倍
由于我无法在搜索中找到任何内容,因此我会在这里问一个问题来尝试运气:
我试图在“客户”集合中创建唯一文档,并且为了确保它们是唯一的,我在集合中的(唯一!)名称字段中进行搜索,以检查是否已经创建了客户。现在,我试图排除区分大小写的双精度字符和空格双精度字符。 (示例客户:“ SpaceX”已经存在,因此我不能创建“ Spacex”或“ SpaceX”或“ Space X”,只是要确保客户的文档是唯一的。)
所以我想做的是使用$regex
遍历索引的名称字段,如果发现了某些内容,则返回错误。
我发现customer.find({name: {$regex: new RegEx(name),$options: 'ix' })
在这种情况下不起作用,但是根据文档,它应该为该名称过滤掉空白的,不区分大小写的文档...。
这让我疯狂。有谁知道如何解决这个问题?
这是我当前用于放置支票的代码:
let existingCustomer
try {
console.log(new RegExp(name),typeof name)
existingCustomer = await Customer.find(
{
name: { $regex: new RegExp(name),$options: 'ix' },},'-products -tam -responsiblePerson -info -created -updated'
)
console.log(existingCustomer)
} catch (err) {}
if (existingCustomer.length > 0) {
console.log(existingCustomer[0])
const error = new HttpError(
'Customer name already exists,please use a different name.',500
)
return next(error)
}
解决方法
您可以这样做:
Customer.find({
name: { $regex: new RegExp("^" +name.replace(/\s/g,''),"i") }
})
但是自mongoose 3.4
起,建议使用case sensitive index
:文档here
所以您可以简单地做:
Customer.find({
name: name.replace(/\s/g,'')
})
.collation( { locale: 'en',strength: 2 } )
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。