如何在Mongoose中的单个文档中索引多个唯一数据字段? [英] How to index multiple unique data fields in a single document in Mongoose?
问题描述
在我的用户文档中,我想分别将 email
和 username
索引为唯一字段,以便永远不会输入重复项.
In my user document, I want to individually index email
and username
as unique fields, so that a duplicate is never entered.
问题在于,我为多个唯一索引找到的所有文档都是针对复合索引"的,它似乎以某种方式将第二个索引与第一个索引绑定在一起.我不要
The problem is all of the documentation I have found for multiple unique indexes is for "Compound Indexing", which appears to somehow tie the second index to the first. I don't want that.
我想要的只是我的注册步骤1 ,如果用户提交的邮件已为MongoDB返回,并且返回的错误与步骤2完全相同,当他们设置用户名时.
All I want is for in my signup step 1 if a user submits an email that already exists for MongoDB to return an error that it already exists, and exact same for step 2, when they set their username.
所以我希望它们的索引和唯一性彼此分开.我现在正在使用它,它以某种方式将2绑在一起,这不是我想要的:
So I want them indexed and unique separate from each other. I'm using this now and it is tieing the 2 together somehow which is not what I want:
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: true,
trim: true
},
username: {
type: String,
required: false,
trim: true
}
})
UserSchema.index({
email: 1,
username: 1
}, {
unique: true
});
推荐答案
猫鼬没有针对唯一字段的内置验证.我推荐该软件包(与此配套的是,您可以在电子邮件和用户名字段上使用唯一验证器):mongoose-unique-validator.使用以下代码扩展代码:
Mongoose doesn't have a built-in validation for unique fields. I recommend the package (with this you can use the unique validator on the email and username fields): mongoose-unique-validator. Extend your code with:
let uniqueValidator = require('mongoose-unique-validator');
email: {
type: String,
required: true,
trim: true,
unique: true,
index: true
},
username: {
type: String,
required: false,
trim: true,
unique: true,
index: true
}
UserSchema.plugin(uniqueValidator, {message: 'is already taken.'});
这篇关于如何在Mongoose中的单个文档中索引多个唯一数据字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!