nodejs操作mongodb
教程:http://ourjs.com/detail/53ad24edb984bb4659000013
Schema
、Model
、Entity
的关系请牢记,Schema
生成Model
,Model
创造Entity
,Model
和Entity
都可对数据库操作造成影响,但Model
比Entity
更具操作性。
我是在http://www.cnblogs.com/wang-jing/p/4138654.html(node.js+express+mongodb)的基础上练习的
1、可以由model生成entity
var personE = new Demo({title:'blog'}); console.log(personE.title);
2、可以在schema中定义方法,在entity中使用:为model和entity提供公共方法
demoSchema.methods.speak = function(){ console.log('my name is:'+this.title); } personE.speak();
schema:是数据库模型在程序中的表现;schema.type是mongoose的数据类型
Schema.Types.Mixed是Mongoose定义个混合类型,碰到了再说
Schema.Types.ObjectId主键
虚拟属性/虚拟域 碰到了再说
配置项:safe,strict,sharedKey(分布式),capped(上线操作),versionKey(版本锁),autoIndex(自动索引)
var ExampleSchema = new Schema(config,options); 或 var ExampleSchema = new Schema(config); ExampleSchema.set(option,value);
Documents:相当于entity
更新
PersonModel.findById(id,function(err,person){ person.name = 'MDragon'; //entity person.save(function(err){}); });
新增:
entity.save(); model.create();
删除:
entity.remove(); model.remove();
子文档 碰到了再说
查询
Person .find({ occupation: /host/ }) .where('name.last').equals('Ghost') .where('age').gt(17).lt(66) .where('likes').in(['vaporizing', 'talking']) .limit(10) .sort('-occupation') .select('name occupation') .exec(callback);
model.find(); model.count()
/* ----------验证-------------- */
验证始终定义在SchemaType中 验证是一个内部中间件 验证是在一个Document被保存时默认启用的,除非你关闭验证 验证是异步递归的,如果你的SubDoc验证失败,Document也将无法保存 验证并不关心错误类型,而通过ValidationError这个对象可以访问
required 非空验证
min/max 范围验证(边值验证)
enum/match 枚举验证/匹配验证
validate 自定义验证规则
var PersonSchema = new Schema({ name:{ type:'String', required:true //姓名非空 }, age:{ type:'Nunmer', min:18, //年龄最小18 max:120 //年龄最大120 }, city:{ type:'String', enum:['北京','上海'] //只能是北京、上海人 }, other:{ type:'String', validate:[validator,err] //validator是一个验证函数,err是验证失败的错误信息 } });
err.errors //错误集合(对象) err.errors.color //错误属性(Schema的color属性) err.errors.color.message //错误属性信息 err.errors.path //错误属性路径 err.errors.type //错误类型 err.name //错误名称 err.message //错误消息