[译]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 ...
随机推荐
- [NOIP2014] 普及组
珠心算测验 模拟. 将所有“两个不同数之和”装进桶里,扫描原数组记录满足条件的数的个数. /*by SilverN*/ #include<iostream> #include<alg ...
- 在Ubuntu上如何往fcitx里添加输入法
Ubuntu 16.04引入了一个新的包管理工具apt, 用法与apt-get类似. 在终端用apt搜索fcitx支持的输入法 apt search fcitx All Fcitx related p ...
- persistent.xml hibernate 利用sql script 自定义生成 table 表
<?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http:// ...
- Python基本数据类型之int
一.int的范围 2.7: 32位:-2^31~2^31-1 64位:-2^63~2^63-1 3.5: 在3.5中init长度理论上是无限的 二.python内存机制 在一般情况下当变量被赋值后,内 ...
- centos搭建https协议的tomcat和apache服务器以及nginx服务器,mysql php
Apache HTTP Server(简称 Apache)是 Apache 软件基金会的一个开放源码的网页服务器,可以在大多数计算机操作系统中运行,由于其多平台和安全性被广泛使用,是最流行的 Web ...
- BZOJ4004: [JLOI2015]装备购买
总之就是线性基那一套贪心理论直接做就好了. 然而加强数据后很卡精度的样子. 于是重点在于这个特技:在整数模意义下搞. #include<cstdio> #include<algori ...
- bigdecimal类型数据的min方法
java.math.BigDecimal.min(BigDecimal val) 返回此BigDecimal和val的最小值. 声明 以下是java.math.BigDecimal.min()方法的声 ...
- sql 列转行 实例
select * from dbo.orders group by custid with cube select custid ,row_number() over(order by e ...
- 10月23日上午PHP数组
正则表达式 1.替换 $s = "hello5world"; $s = preg_replace("/\d/","#",$s); echo ...
- Java排序算法——归并排序
import java.util.Arrays; //================================================= // File Name : MergeSor ...