转自:https://www.bbsmax.com/A/pRdBnKpPdn/

定义schema

用mongoose的第一件事情就应该是定义schema. schema是什么呢? 它类似于关系数据库的表结构.

1
2
3
4
5
6
7
8
9
10
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);

1
var BlogModel = mongoose.model('Blog', blogSchema);

实例化方法

model的实例是document. document有许多内置的实例方法. 我们可以为document定义自己的实例方法

1
2
3
4
5
6
var animalSchema = new Schema({name: String, type: String});
 
//定义实例方法
animalSchema.methods.findSimilarType = function(cb){
  return this.model('Animal').find({type: this.type}, cb);
}

现在animal实例有findSimilarTypes方法了

1
2
3
4
5
6
var Animal = mongoose.model('Animal', animalSchema);
var dog = new Animal({type: 'dog'});
 
dog.findSimilarTypes(function(err, dogs){
  console.log(dogs);
});

Model静态方法

还可以给Model添加静态方法

1
2
3
4
5
6
7
8
9
10
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索引

1
2
3
4
5
6
7
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

1
2
3
animalSchema.set('autoIndex'false);
//or
new Schema({}, {autoIndex: false});

Virtual

virtual是document的属性 你可以get,set他们但是不持续化到MongoDB. virtual属性get非常有用可以格式化或者合并字段,  set可以分解一个字段到多个字段并持续化到数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
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的全名 你需要这样做

1
console.log(bad.name.first + ' ' + bad.name.last);

或者我们可以在personSchema中定义virtual getter. 这样我们就不需要在每个要用fullname的地方拼接字符串了

1
2
3
personSchema.virtual('name.full').get(function(){
    return this.name.first + ' ' this.name.last; 
);

现在我么可以使用 name.full虚属性了

1
console.log(bad.name.full);

我们还可以通过设置this.name.full来设置this.name.first和this.name.last

1
bad.name.full = "Breaking Bad";
1
2
3
4
5
6
7
8
9
10
11
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有一些配置选项, 可以如下面一样设置

1
2
3
4
5
new Schema({}, options);
 
//or
var xxSchema = new Schema({});
xxSchema.set(option, value);

option:autoIndex

应用启动的时候Mongoose会自动为每一个schema发送一个ensureIndex命令。  如果你想禁止自动创建index要自己手动来创建的话 你可以设置autoIndex为false

1
2
3
4
var xxSchema = new Schema({}, { autoIndex: false });
 
var Clock = mongoose.model('Clock', xxSchema);
Clock.ensureIndexs(callback);

option:bufferCommands

todo

1
var schema = new Schema({}, { bufferCommands: false });

option:capped

todo

....

85.Mongoose指南 - Schema的更多相关文章

  1. [译]Mongoose指南 - Schema

    定义schema 用mongoose的第一件事情就应该是定义schema. schema是什么呢? 它类似于关系数据库的表结构. var mongoose = require('mongoose'); ...

  2. [译]Mongoose指南 - Population

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

  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 建立schema 和model

    在node中使用MongoDB很多情况下,都是使用mongoose的,所以这集来介绍一下 安装 yarn add mongoose 连接 const mongoose = require(" ...

  6. [译]Mongoose指南 - Connection

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

  7. [译]Mongoose指南 - Plugin

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

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

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

  9. [译]Mongoose指南 - 查询

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

随机推荐

  1. Crazyflie 2.0 System Architecture

    Crazyflie 2.0架构包含两个微控制器: A NRF51, Cortex-M0, 用于实现无线通信和电源管理: (1)按键开关逻辑(ON/OFF logic) (2)控制给其它系统供电(STM ...

  2. 图片3d轮放查看效果

    本功能比較简单,就是一个大幕.左右滚动播放图片. 关键点在于怎样实现平滑的滚动,包含动画效果,3d效果等. <style> img { position: absolute; top:20 ...

  3. 在fragment中显示对话框出现异常

    异常类型为:android.view.WindowManager$BadTokenException: Unable to add window 我在fragment中public View onCr ...

  4. MVC 从View像Controller中传值

    在上一篇博客中总结了一下从Controller像View中传值的几种方法.事实上看那些方法和在我们最初学习VB的时候一样,将数据库中的数据显示到前台的页面.数据库还是那个数据库,仅仅是如今前台变成了浏 ...

  5. UVALive 4225 / HDU 2964 Prime Bases 贪心

    Prime Bases Problem Description Given any integer base b >= 2, it is well known that every positi ...

  6. 继承QWidget的派生类控件不能设置QSS问题解决(使用style()->drawPrimitive(QStyle::PE_Widget,也就是画一个最简单最原始的QWidget,不要牵扯其它这么多东西)

    自定义控件时基类用了QWidget,发现qss设置不起作用,需要重载其paintEvent函数即可: 如下代码: void CCustomWidget::paintEvent(QPaintEvent* ...

  7. Java多线程编程模式实战指南(三):Two-phase Termination模式--转载

    本文由本人首次发布在infoq中文站上:http://www.infoq.com/cn/articles/java-multithreaded-programming-mode-two-phase-t ...

  8. Android开发中,9-patch (九宫格)图片作为背景带来的问题

    9-patch 为了解决不同分屏下的图片适应性,对图片做了padding,而在android中,要给一个控件设置背景图,最终是要调用 setBackgroundDrawable  方法来设置图片资源, ...

  9. POJ 3253 Fence Repair C++ STL multiset 可解 (同51nod 1117 聪明的木匠)

    Fence Repair Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 53106   Accepted: 17508 De ...

  10. ActiveMQ学习笔记(15)----Message Dispatch高级特性(一)

    1. Message Cursors 1.1 概述 ActiveMQ发送持久化消息的典型的厝里方式是:当消息的消费者准备就绪时,消息发送系统把存储的消息按批次发送给消费者,在发送完一个批次的消息后,指 ...