mongoose设置unique不生效问题的解决及如何移除unique的限制
前言
unique属于schema约束验证中的一员,他的作用主要就是让某一个字段的值具有唯一性(不能重复)
保持字段的唯一性使用type值:{type:String,unique:true,dropDups:true}
注意:mongoose一旦修改了数据存储的机构,数据库一定要重启,很多新手在设置一些属性不生效时都是这个原因
这里说的重启,不是简单的关闭mongoose数据库服务器重新打开,而是先将该数据库整个删除,然后再重启数据库服务
简单的schema特殊用法示例
//导入模块
varmongoose=require('mongoose');
//连接数据库
mongoose.connect('mongodb://localhost/itheima');
//创建schema
//schema第一个参数是我们自定义的数据类型第二个参数是管理schema默认的数据类型
varstudentSchema=mongoose.Schema({
name:{type:String,required:true},//数据类型为string,不能非空
age:{type:Number,default:18},//数据类型为string,默认值18
study_id:{type:Number,select:true},//学号,默认查询字段
address:{type:String,lowercase:true},//地址,默认小写
email:{type:String,match:RegExp(/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/)},//邮箱,正则表达式验证
phone:{type:String,unique:true,dropDups:true}//电话号码唯一性
},{
versionKey:false,//去掉版本锁__v0
timestamps:{createdAt:'createTime',updatedAt:'updateTime'}//自动管理修改时间
});
//创建model
varstudent=mongoose.model('student',studentSchema);
//创建Entity
varzhangsan=newstudent({
name:'zhangsan',//名字必须要有,否则会报错:name:Path`name`isrequired.
address:'ZhongLiang',//字符串都会变成小写
email:'a12345@qq.com',//邮箱格式不对,添加会报错Path`email`isinvalid(a12345qq.com).
study_id:2017001,
phone:'123456789'//在添加唯一性字段时,mongoose会先查询数据库所有的phone值,一旦发现该值已存在则会报错
});
//添加数据
student.create(zhangsan,function(err){
if(err){
throwerr;
}
console.log('插入成功'+zhangsan);
});
Mongoose移除unique的限制
程序中email最开始设置了unque限制,导致email在此collection中无法重复插入,现在想要移除unique限制。
db.your_collection.dropIndexes();
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。