如何在猫鼬模型上使用partialFilterExpression [英] How can I use partialFilterExpression on a mongoose model
问题描述
我创建了一个带有电子邮件字段的猫鼬模型.如果用户提供了一个值,我希望它是唯一的,但是如果用户未提供任何值,我希望它为空.我在这里找到了一个很好的mongodb参考: https://docs.mongodb.com/manual/core/index-partial/#partial-index-with-unique-constraints 可以工作,但我不知道如何使它在猫鼬上工作 >
这是该字段现在的样子
email: {
type: String,
index: true,
unique: true
}
如果保持原样,我将无法使用电子邮件字段为空/空创建多个文档
在电子邮件路径级别,您只能使用:
email: {
type: String
}
在架构级别使用:
SchemaName.index({ email: 1 }, {
unique: true,
partialFilterExpression: {
'email': { $exists: true, $gt: '' }
}
});
这样,仅当电子邮件存在且不是空字符串时,才应用唯一约束
I have created a mongoose model that has an email field. I want it to be unique if a value is provided by a user but I want it to be empty is a user has not provided any value. I have found a good mongodb reference here: https://docs.mongodb.com/manual/core/index-partial/#partial-index-with-unique-constraints that could work but I don't know how to make it work on mongoose
This is how the field looks like right now
email: {
type: String,
index: true,
unique: true
}
If I leave it the way it is, I cant create multiple documents with an empty/null email field
In the email path level, you can use only:
email: {
type: String
}
And in the schema level use:
SchemaName.index({ email: 1 }, {
unique: true,
partialFilterExpression: {
'email': { $exists: true, $gt: '' }
}
});
This way the unique constraint is applied only if email exists and is not an empty string
这篇关于如何在猫鼬模型上使用partialFilterExpression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!