您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
三六零分类信息网 > 林芝分类信息网,免费分类信息发布

移除unique限制的方法

2026/1/27 2:05:11发布36次查看
这次给大家带来移除unique限制的方法,移除unique限制的注意事项有哪些,下面就是实战案例,一起来看一下。
前言
unique属于schema约束验证中的一员,他的作用主要就是让某一个字段的值具有唯一性(不能重复)
保持字段的唯一性使用type值: {type:string,unique:true,dropdups: true}
注意:mongoose一旦修改了数据存储的机构,数据库一定要重启,很多新手在设置一些属性不生效时都是这个原因
这里说的重启,不是简单的关闭mongoose数据库服务器重新打开,而是先将该数据库整个删除,然后再重启数据库服务
简单的schema特殊用法示例
//导入模块 var mongoose = require('mongoose'); //连接数据库 mongoose.connect('mongodb://localhost/itheima'); //创建schema //schema第一个参数是我们自定义的数据类型 第二个参数是管理schema默认的数据类型 var studentschema = 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 var student = mongoose.model('student',studentschema); //创建entity var zhangsan = new student({  name:'zhangsan',//名字必须要有,否则会报错: name: path `name` is required.  address:'zhongliang',//字符串都会变成小写  email:'a12345@qq.com',//邮箱格式不对,添加会报错 path `email` is invalid (a12345qq.com).  study_id:2017001,  phone:'123456789'//在添加唯一性字段时,mongoose会先查询数据库所有的phone值,一旦发现该值已存在则会报错 }); //添加数据 student.create(zhangsan,function(err){  if(err){   throw err;  }  console.log('插入成功' + zhangsan); });
mongoose 移除unique的限制
程序中email最开始设置了unque限制,导致email在此collection中无法重复插入,现在想要移除unique限制。
db.your_collection.dropindexes();
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
js实现导航栏的透明渐变
node的模块系统使用详解
在bootstrap里怎么操作table
以上就是移除unique限制的方法的详细内容。
林芝分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product