database operations mongoose 2

 The main function of the built-in explanation of mongoose


In addition to defining document structure and type of data you want to store. Mode ( the Schema ) is further configured to define the following:

·         Validators (asynchronous and synchronous)

·         Defaults - default value

·        Getters

·        Setters

·         The Indexes - Index

·         Middleware - Middleware

·         Methods Definition - method definition

·         Statics Definition - statically defined

·         Plugins - plug-in

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) validator

Verification by defined ShcemaType

Internal use middleware

When using the default save operating on their own initiative to open (create, whether action should be used, that we can give it a try)

Use asynchronous operation

Validator can define your own

 

 

By custom validation. path ( "attribute") .validate (function (value) {}) is defined, we look at the examples:

<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>

 

Guess you like

Origin www.cnblogs.com/ldxsuanfa/p/10960332.html