定义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的更多相关文章

  1. [译]Mongoose指南 - Population

    MongoDB没有join, 但是有的时候我们需要引用其它collection的documents, 这个时候就需要populate了. 我们可以populate单个document, 多个docum ...

  2. 85.Mongoose指南 - Schema

    转自:https://www.bbsmax.com/A/pRdBnKpPdn/ 定义schema 用mongoose的第一件事情就应该是定义schema. schema是什么呢? 它类似于关系数据库的 ...

  3. [译]Mongoose指南 - 验证

    开始前记住下面几点 Validation定义在SchemaType中 Validation是一个内部的中间件 当document要save前会发生验证 验证不会发生在空值上 除非对应的字段加上了 re ...

  4. [译]Mongoose指南 - Model

    编译你的第一个model var xxSchema = new Schema({name: 'string', size: 'string'}); var Tank = mongoose.model( ...

  5. [译]Mongoose指南 - Connection

    使用mongoose.connect()方法创建连接 mongoose.conect('mongodb://localhost/myapp'); 上面的代码是通过默认端口27017链接到mongodb ...

  6. [译]Mongoose指南 - Plugin

    Schema支持插件, 这样你就可以扩展一些额功能了 下面的例子是当document save的时候自定更新最后修改日期的出插件 // lastMod.js module.exports = expo ...

  7. [译]Mongoose指南 - 中间件

    中间件是一些函数, 当document发生init, validate, save和remove方法的时候中间件发生. 中间件都是document级别的不是model级别的. 下面讲讲两种中间件pre ...

  8. [译]Mongoose指南 - 查询

    查询有带callback和不带callback两种方式 所有mongoose的callback都是这种格式: callback(err, result) var Person = mongoose.m ...

  9. [译]Mongoose指南 - Document

    更新 有几种方式更新document. 先看一下传统的更新方法 Tank.findById(id, function(err, tank){ if(err) return handleError(er ...

随机推荐

  1. Deformity ASP/ASPX Webshell、Webshell Hidden Learning

    catalog . Active Server Page(ASP) . ASP.NET . ASP WEBSHELL变形方式 . ASPX WEBSHELL变形方式 . webshell中常见的编码转 ...

  2. struts2 CVE-2012-0392 S2-008 Strict DMI does not work correctly allows remote command execution and arbitrary file overwrite

    catalog . Description . Effected Scope . Exploit Analysis . Principle Of Vulnerability . Patch Fix 1 ...

  3. iOS应用第三方推送的添加

    现在的一些第三方的推送平台挺好用,主要是因为他们有类似微信公众平台一样的管理后台,简单易用,封装了很多开发者需要的推送功能. 下面以个推为例: 1.在个推的应用配置iOS部分设置自己的BounleID ...

  4. [iOS Keychain本地长期键值存储]

    目前本地存储方式大致有:Sqlite,Coredata,NSUserdefaults.但他们都是在删除APP后就会被删除,如果长期使用存储,可以使用Keychain钥匙串来实现. CHKeychain ...

  5. Maven中配置maven-compiler-plugin插件

    这个插件就如同名字所显示的这样,用来编译源代码的. 加载第三方包 <dependency> <groupId>cn.eshore.bnet</groupId> &l ...

  6. POJ 1061青蛙的约会(拓展欧几里德算法)

    题目链接: 传送门 青蛙的约会 Time Limit: 1000MS     Memory Limit: 65536K Description 两只青蛙在网上相识了,它们聊得很开心,于是觉得很有必要见 ...

  7. Linux之:Ubuntu速学笔记(2)

    撰写日期:2016-7-3 18:20:39 基本内容包括:Flash player安装.编译安装PHP.写个简单的PHP程序:Java程序(Java需要使用“javac”命令编译一下才能执行) 一. ...

  8. Hough Transform

    Hough Transform Introduction: The Hough transform is an algorithm that will take a collection of poi ...

  9. JPA事务总结

    http://www.soso.io/article/65405.html 事务管理是JPA中另一项重要的内容,了解了JPA中的事务管理,能够进一步掌握JPA的使用.事务管理是对一系列操作的管理,它最 ...

  10. Linux命令(31):zip/unzip命令-打包压缩

    zip命令功能说明    zip程序即是文件压缩工具也是文件归档工具,可以对文件或者目录进行压缩或解压,压缩格式为zip.在Linux系统中,gzip才是主要的压缩指令,而bzip2仅次之.Linux ...