mongoose 数据库操作2

 mongoose的内置的主要功能解说


除了定义文档结构和你要存储的数据类型外。模式(Schema)还用于下面定义:

·        Validators (异步和同步)

·        Defaults - 默认值

·        Getters

·        Setters

·        Indexes - 索引

·        Middleware - 中间件

·        Methods definition - 方法定义

·        Statics definition - 静态定义

·        Plugins - 插件

Aside from defining thestructure of your documents and the types of data you're storing, a Schemahandles the definition of:

·        Validators (async andsync)

·        Defaults

·        Getters

·        Setters

·        Indexes

·        Middleware

·        Methods definition

·        Statics definition

·        Plugins

·        pseudo-JOINs

 

(1)验证器

验证器通过ShcemaType定义

内部使用中间件

默认在使用save操作时自己主动开启(create操作应该是无论用的,这个我们能够试一试)

使用异步操作

验证器能够自己定义

 

 

定义验证通过。path(“属性”).validate(function(value){})来定义,我们看看样例:

<pre name="code" class="javascript">

var toySchema = newSchema({

  color: String,

  name: String

});

 

var Toy = mongoose.model('Toy', toySchema);

 

Toy.schema.path('color').validate(function (value) {

  return /blue|green|white|red|orange|periwinkle/i.test(value);

}, 'Invalid color');

 

var toy = new Toy({ color: 'grease'});

 

toy.save(function (err) {

  // err is ourValidationError object

  // err.errors.coloris a ValidatorError object

 

 console.log(err.errors.color.message) // prints'Validator "Invalid color" failed for path color with value `grease`'

 console.log(String(err.errors.color)) // prints'Validator "Invalid color" failed for path color with value `grease`'

 console.log(err.errors.color.type) // prints "Invalid color"

 console.log(err.errors.color.path) // prints "color"

 console.log(err.errors.color.value) // prints"grease"

  console.log(err.name) // prints"ValidationError"

  console.log(err.message) // prints"Validation failed"

});

</pre>

 

上面的样例非常easy嘛。

假设用不到验证的方法那么。直接create 就能够

Toy.create({xx:xxx},function(err,schema){});

 

(2)默认值

 

上样例:

<pre name="code" class="javascript">

var schema = new Schema({ n: { type: Number, default: 10 })

var M = db.model('M', schema)

var m = new M;

console.log(m.n) // 10

</pre>

 

在方案(Schema)设置defualt值后,值初始化模型后就能够直接获取这个值,那么我们在插入操作中要怎样去做呢?

<pre name="code" class="javascript">

var db = require('mongoose')

,Schema = db.Schema;

var schema = new Schema({ n: { type: Number, default: 10 }});

db.connect('mongodb://localhost:8888/toy', function (err) {

    var Toy = db.model('Toy', schema,"toy");

    new Toy({}).save(function(err){

        if(err)return console.log(err);

        console.log("报错成功");

    });

    if (err) throw err;

});

</pre>

这个样例中关键的地方在于new Toy({}) 并没有写n这个对象,那么我们来查一下数据库看一下输出:

<pre name="code" class="javascript">

> db.toy.find()

{ "_id" : ObjectId("5361a5fa62c7cc803624ec0d"),"n" : 10, "__v" : 0 }

</pre>

 

 

(3)给模型加入一个静态的方法:

<pre name="code" class="javascript">

// assign afunction to the "statics" object of our animalSchema

animalSchema.statics.findByName = function (name, cb) {

  this.find({ name: newRegExp(name, 'i') }, cb);

}

 

var Animal = mongoose.model('Animal',animalSchema);

Animal.findByName('fido', function (err, animals) {

  console.log(animals);

});

</pre>

 

(4)创建索引:

 

在mongodb数据库中索引排序1 和 -1 代表正反

<pre name="code" class="javascript">

 

var animalSchema= new Schema({

  name: String,

  type: String,

  tags: { type: [String], index: true } // field level

});

 

animalSchema.index({ name: 1, type: -1 }); // schema level

</pre>

 

(5)插件就是mongoose提供的一个能够模块化的一个功能,能够把面的一些零散的功能写到一个插件中组合起来,比方set get 方法中间件等写到一个模块中:

 

<pre name="code" class="javascript">

 

// lastMod.js

module.exports = exports =function lastModifiedPlugin (schema, options){

  schema.add({ lastMod: Date })

 

  schema.pre('save', function (next) {

    this.lastMod = new Date

    next()

  })

 

  if(options && options.index) {

    schema.path('lastMod').index(options.index)

  }

}

 

// game-schema.js

var lastMod= require('./lastMod');

varGame = new Schema({ ... });

Game.plugin(lastMod, {index: true });

 

// player-schema.js

varlastMod = require('./lastMod');

varPlayer = new Schema({ ... });

Player.plugin(lastMod);

</pre>

 

猜你喜欢

转载自www.cnblogs.com/ldxsuanfa/p/10960332.html
今日推荐