mongoose設置unique不生效問題的解決及如何移除unique的限制
前言
unique屬于schema約束驗證中的一員,他的作用主要就是讓某一個字段的值具有唯一性(不能重復)
保持字段的唯一性使用type值: {type:String,unique:true,dropDups: true}
注意:mongoose一旦修改了數(shù)據(jù)存儲的機構,數(shù)據(jù)庫一定要重啟,很多新手在設置一些屬性不生效時都是這個原因
這里說的重啟,不是簡單的關閉mongoose數(shù)據(jù)庫服務器重新打開,而是先將該數(shù)據(jù)庫整個刪除,然后再重啟數(shù)據(jù)庫服務
簡單的schema特殊用法示例
//導入模塊
var mongoose = require('mongoose');
//連接數(shù)據(jù)庫
mongoose.connect('mongodb://localhost/itheima');
//創(chuàng)建schema
//schema第一個參數(shù)是我們自定義的數(shù)據(jù)類型 第二個參數(shù)是管理schema默認的數(shù)據(jù)類型
var studentSchema = mongoose.Schema({
name:{type:String,required:true},//數(shù)據(jù)類型為string,不能非空
age:{type:Number,default:18},//數(shù)據(jù)類型為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' }//自動管理修改時間
});
//創(chuàng)建model
var student = mongoose.model('student',studentSchema);
//創(chuàng)建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會先查詢數(shù)據(jù)庫所有的phone值,一旦發(fā)現(xiàn)該值已存在則會報錯
});
//添加數(shù)據(jù)
student.create(zhangsan,function(err){
if(err){
throw err;
}
console.log('插入成功' + zhangsan);
});
Mongoose 移除unique的限制
程序中email最開始設置了unque限制,導致email在此collection中無法重復插入,現(xiàn)在想要移除unique限制。
db.your_collection.dropIndexes();
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關文章
webstorm中配置nodejs環(huán)境及npm的實例
今天小編就為大家分享一篇webstorm中配置nodejs環(huán)境及npm的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05
Node使用Sequlize連接Mysql報錯:Access denied for user ‘xxx’@‘localh
這篇文章主要給大家介紹了關于Node使用Sequlize連接Mysql報錯:Access denied for user 'xxx'@'localhost'的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面隨著小編來一起學習學習吧。2018-01-01
node?gyp安裝canvas原生模塊編譯node?pregyp詳解
這篇文章主要為大家介紹了Nodejs關于原生模塊編譯node-gyp + node-pre-gyp (以安裝canvas為例)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11

