[译]Mongoose指南 - Schema
定义schema
用mongoose的第一件事情就应该是定义schema. schema是什么呢? 它类似于关系数据库的表结构.
var mongoose = require('mongoose');
var schema = mongoose.Schema;
var blogSchema = new Schema({
titile: String,
body: String,
comments: [{body: String, date: Date}],
date: {type: Date, default: Date.now},
hidden:Boolen
});
创建model
格式是mongoose.model(modelName, schema);
var BlogModel = mongoose.model('Blog', blogSchema);
实例化方法
model的实例是document. document有许多内置的实例方法. 我们可以为document定义自己的实例方法
var animalSchema = new Schema({name: String, type: String});
//定义实例方法
animalSchema.methods.findSimilarType = function(cb){
return this.model('Animal').find({type: this.type}, cb);
}
现在animal实例有findSimilarTypes方法了
var Animal = mongoose.model('Animal', animalSchema);
var dog = new Animal({type: 'dog'});
dog.findSimilarTypes(function(err, dogs){
console.log(dogs);
});
Model静态方法
还可以给Model添加静态方法
animalSchema.statics.findByName = function(name, cb){
this.find({name: new RegExp(name, 'i')}, cb);
}
var Animal = mongoose.model('Animal', animalSchema);
Animal.findByName('fido', function(err, animals){
console.log(animals);
});
索引
索引分为field级别和schema级别. 如果使用复合索引那么必须使用schema索引
var animalSchema = new Schema({
name: String,
type: String,
tags: {type: [String], index:true} // field level
});
animalSchema.index({name:1, type:-1}); // schema level
当应用启动的时候, mongoose会自动为你的schema调用ensureIndex确保生成索引. 开发环境用这个很好, 但是建议在生产环境不要使用这个.使用下面的方法禁用ensureIndex
animalSchema.set('autoIndex', false);
//or
new Schema({}, {autoIndex: false});
Virtual
virtual是document的属性 你可以get,set他们但是不持续化到MongoDB. virtual属性get非常有用可以格式化或者合并字段, set可以分解一个字段到多个字段并持续化到数据库
var personSchema = new Schema({
name: {
first: String,
last: String
}
});
var Person = mongoose.model('Person', personSchema);
var bad = new Person({
name: {first: 'Walter', last: 'White'}
});
如果你想获取bad的全名 你需要这样做
console.log(bad.name.first + ' ' + bad.name.last);
或者我们可以在personSchema中定义virtual getter. 这样我们就不需要在每个要用fullname的地方拼接字符串了
personSchema.virtual('name.full').get(function(){
return this.name.first + ' ' + this.name.last;
);
现在我么可以使用 name.full虚属性了
console.log(bad.name.full);
我们还可以通过设置this.name.full来设置this.name.first和this.name.last
bad.name.full = "Breaking Bad";
personSchema.virtual('name.full').set(function(name){
var split = name.split(' ');
this.name.first = split[0];
this.name.last = split[1];
});
mad.name.full = "Breaking Bad";
console.log(mad.name.first); // Breaking
console.log(mad.name.last); // Bad
Options
Schema有一些配置选项, 可以如下面一样设置
new Schema({}, options);
//or
var xxSchema = new Schema({});
xxSchema.set(option, value);
option:autoIndex
应用启动的时候Mongoose会自动为每一个schema发送一个ensureIndex命令。 如果你想禁止自动创建index要自己手动来创建的话 你可以设置autoIndex为false
var xxSchema = new Schema({}, { autoIndex: false });
var Clock = mongoose.model('Clock', xxSchema);
Clock.ensureIndexs(callback);
option:bufferCommands
todo
var schema = new Schema({}, { bufferCommands: false });
option:capped
todo
....
[译]Mongoose指南 - Schema的更多相关文章
- [译]Mongoose指南 - Population
MongoDB没有join, 但是有的时候我们需要引用其它collection的documents, 这个时候就需要populate了. 我们可以populate单个document, 多个docum ...
- 85.Mongoose指南 - Schema
转自:https://www.bbsmax.com/A/pRdBnKpPdn/ 定义schema 用mongoose的第一件事情就应该是定义schema. schema是什么呢? 它类似于关系数据库的 ...
- [译]Mongoose指南 - 验证
开始前记住下面几点 Validation定义在SchemaType中 Validation是一个内部的中间件 当document要save前会发生验证 验证不会发生在空值上 除非对应的字段加上了 re ...
- [译]Mongoose指南 - Model
编译你的第一个model var xxSchema = new Schema({name: 'string', size: 'string'}); var Tank = mongoose.model( ...
- [译]Mongoose指南 - Connection
使用mongoose.connect()方法创建连接 mongoose.conect('mongodb://localhost/myapp'); 上面的代码是通过默认端口27017链接到mongodb ...
- [译]Mongoose指南 - Plugin
Schema支持插件, 这样你就可以扩展一些额功能了 下面的例子是当document save的时候自定更新最后修改日期的出插件 // lastMod.js module.exports = expo ...
- [译]Mongoose指南 - 中间件
中间件是一些函数, 当document发生init, validate, save和remove方法的时候中间件发生. 中间件都是document级别的不是model级别的. 下面讲讲两种中间件pre ...
- [译]Mongoose指南 - 查询
查询有带callback和不带callback两种方式 所有mongoose的callback都是这种格式: callback(err, result) var Person = mongoose.m ...
- [译]Mongoose指南 - Document
更新 有几种方式更新document. 先看一下传统的更新方法 Tank.findById(id, function(err, tank){ if(err) return handleError(er ...
随机推荐
- Code笔记之:对使用zend加密后的php文件进行解密
对使用zend加密后的php文件进行解密 使用zend加密后的php文件用notpad++打开会出现类似的乱码 下面使用解密工具进行解密 http://pan.baidu.com/s/1i3n4ysX ...
- 今天执行grep命令差点把服务器搞崩
grep "rst" -r ./ >> a.log 今天执行这个命令差点把服务器搞崩了. 本意是查找所有源代码文件中含有rst字符串的行,打印到文件a.log中,然后进 ...
- Node-webkit简介
Node-webkit 概述 Node-webkit 是Github 上一个非常热门的开源项目,它基于著名的浏览器开源项目 Chromium 和服务器端 JavaScript 实现 Node.js 的 ...
- Python ValueError: IO operation on closed file
ValueError IO operation on closed file表示处理了已经被关闭的数据,在python 中 with语句的上下文会帮助处理,也就是说,当python的处理代码不对齐的时 ...
- JavaWeb---总结(十四)JSP原理
一.什么是JSP? JSP全称是Java Server Pages,它和servle技术一样,都是SUN公司定义的一种用于开发动态web资源的技术. JSP这门技术的最大的特点在于,写jsp就像在写h ...
- Yocto开发笔记之《工具使用:TFTP & NFS & SSH》(QQ交流群:519230208)
QQ群:519230208,为避免广告骚扰,申请时请注明 “开发者” 字样 ======================================================== TFTP工 ...
- JAVA Socket超时浅析
JAVA Socket超时浅析 套接字或插座(socket)是一种软件形式的抽象,用于表达两台机器间一个连接的"终端".针对一个特定的连接,每台机器上都有一个"套接字&q ...
- python 内建函数setattr() getattr()
python 内建函数setattr() getattr() setattr(object,name,value): 作用:设置object的名称为name(type:string)的属性的属性值为v ...
- 入门:HTML:hello world!
<html> <head> </head> <body> <h1>hello world!</h1> </body> ...
- codeforces 697B Barnicle
题目链接:http://codeforces.com/problemset/problem/697/B 题目大意: 将科学计数法用十进制表示.[如果类似于7.0应输出7] 解题思路: Java 中 B ...