赞
踩
在前几个操作中打开数据库发现并没有stu
,是因为我们还没有往里边添加数据,当我们开始往里边添加数据时我们就可以看到一个有数据的stu
数据库.
数据库链接和构建模板的准备工作
//mongoose--用来操作mongodb数据的模块 let mongo = require('mongoose'); //1.链接MongoDB server // mongo.connect('mongodb://user:password@ip/dbname'); mongo.connect('mongodb://127.0.0.1:27017/stu',{ useNewUrlParser: true , useUnifiedTopology: true ,useCreateIndex:true},function(){ console.log("链接完成"); });//callback链接完成之后的函数 //2.将mongoose内置的Promise对象手动修改成使用ES6的Promise对象 mongo.Promise = global.Promise;//promise诺言 //3.获取默认的链接数据库对象 const db = mongo.connection;//const定义一个值不可改变的量,connection默认链接的数据库 //4.判断链接是否失败 db.on('error',function(err){ if(!err){ console.log("链接成功"); } else{ console.log("链接失败"); } }); //5.构建一个集合模板实例 const entry = new mongo.Schema({ //定义每一个字段 name:{ //检验器,监测数据 type:String,//类型:字符串 maxlength:200,//字节的最大长度 default:null,//默认值为空 required:true,//必须字段 }, age:{ type:Number, min:0, max:40, }, tel:{ type:String, match:/^1\d{10}$/,//正则验证 unique:true,//数据不能重复,字段验证器 } }); //6.根据生成的模板创建一个数据模型 const stu = db.model('stu',entry);//model模型,第一个属性name第二个属性schema
stu.create({'name':'张三','age':18,'tel':'12345678912'},function(err,val){
console.log(val);
})
多了两个索引:id默认作为查找当前数据的唯一索引
将多条数据放到一个数组里,如果重复插入相同的数据,val会显示undefined
stu.create([{'name':'张三','age':18,'tel':'12345678912' },
{'name':'李四','age':18,'tel':'12345678913' },
{'name':'王二','age':18,'tel':'12345678914' }],
function(err,val){
console.log(val);
});
unique:true
比如要给电话设置不能重复:
unique="true"的作用是:
若指定为True,则重复出现的记录仅保留一条;若指定为False,则筛选出所有符合条件的记录。默认值为 False。
一旦把一个字段设置成唯一,这个唯一的字段就会被当成一个索引来使用.
tel:{
type:String,
match:/^1\d{10}$/,//正则验证
unique:true,//数据不能重复,字段验证器
}
在mongoose模式中定义索引会出现一个警告
(node:3812) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
collection.ensureIndex已经废用,改用createIndexes。
默认情况下,Mongoose 调用MongoDB驱动程序的ensureIndex()
函数。MongoDB驱
动程序不赞成使用此函数createIndex()
。设置useCreateIndex
全局选项以选择使用Mongoose createIndex()
。
mongo.connect('mongodb://127.0.0.1:27017/stu',{ useNewUrlParser: true , useUnifiedTopology: true ,useCreateIndex:true},function(){
console.log("链接完成");
});
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。