英文:
Unique in mongoose not working as expected
问题
以下是您要翻译的内容:
我有一个示例的mongoose模式如下:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const exampleSchema = new Schema ({
name:{
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
mobile:{
type: String,
required: true,
unique: true
}
})
module.exports ={Driver: mongoose.model('Driver', driverSchema)}
现在的问题是,手机上的唯一性正常工作,但在电子邮件中允许我插入重复的电子邮件地址。
英文:
I have my example mongoose schema as below
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const exampleSchema = new Schema ({
name:{
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
mobile:{
type: String,
required: true,
unique: true
}
})
module.exports ={Driver: mongoose.model('Driver', driverSchema)}
Now the thing is that unique in mobile is working fine, but in email it allows me to insert duplicate email address.
答案1
得分: 1
你最好在mongodb shell中创建你的索引。
在mongoose文档中,他们提到:
> 在生产环境中,你应该使用MongoDB shell来创建你的索引,而不是依赖mongoose来为你做这个。模式的唯一选项在开发和文档编写方面很方便,但mongoose不是索引管理解决方案。
因此,我会从模式中移除唯一选项,然后可以像这样在mongodb shell中创建唯一索引:
db.drivers.createIndex( { "email": 1 }, { unique: true } )
db.drivers.createIndex( { "mobile": 1 }, { unique: true } )
英文:
You had better to create your indexes in mongodb shell.
In the mongoose docs they state:
> In a production environment, you should create your indexes
> using the MongoDB shell rather than relying on mongoose to do it for
> you. The unique option for schemas is convenient for development and
> documentation, but mongoose is not an index management solution.
So I would remove unique options in schema, and can create the unique indexes in mongodb shell like this:
db.drivers.createIndex( { "email": 1 }, { unique: true } )
db.drivers.createIndex( { "mobile": 1 }, { unique: true } )
答案2
得分: 0
这是由于在添加 unique: true
之前,我在集合中有记录。
英文:
It was due to I have records in collection before giving unique: true
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论