MongoDBNode.js专题Liees 技术分享

mongoose.Schema

2017-06-26  本文已影响156人  Liees

Mongoose.Scema基础学习


名词解释

Schema、Model、Entity 的关系请牢记,Schema 生成 Model,Model 创造 Entity,Model 和 Entity 都可对数据库操作造成影响,但 Model 比 Entity 更具操作性。

在学习 mongodb 的过程中需要熟悉几个名词以及他们对应的关系型数据库名词。

关系型数据库 mongodb
table collection
row document
column index
table joins populate
primary key _id

Schema

定义 Schema

mongoose 中任何任何事物都是从 Schema 开始的。每一个 Schema 对应 MongoDB 中的一个集合(collection)。Schema 中定义了集合中文档(document)的样式。

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var blogSchema = new Schema({
    title:  String,
    author: String,
    body:   String,
    comments: [{ body: String, date: Date }],
    date: { type: Date, default: Date.now },
    hidden: Boolean,
    meta: { votes: Number, favs: Number}
});

如果之后想要在Schema中添加键,可以使用Schema#add方法。

Schema.Type

expmale:

var Schema = new Schema({
    name: String,
    binary: Buffer,
    isDeleted: Boolean,
    updated: Date,
    age: Number,
    mixed:Schema.Types.Mixed,
    _id:Schema.Types.ObjectId,  //主键
    _fk:Schema.Types.ObjectId,  //外键
    array: [],
    arrOfString: [String],
    arrOfNumber: [Number],
    arrOfDate: [Date],
    arrOfBuffer: [Buffer],
    arrOfBoolean: [Boolean],
    arrOfMixed: [Schema.Types.Mixed],
    arrOfObjectId: [Schema.Types.ObjectId],
    nested:{
        stuff: String,
    }
})

Buffer 和 ArrayBuffer 是 Nodejs 两种隐藏的对象,相关内容请查看 NodeJS-API

Schema.Type.Mixed

Schema.Types.Mixed 是 Mongoose 定义个混合类型,该混合类型如果未定义具体形式

var AnySchema = new Schema({any:{}})
var AnySchema = new Schema({any:Schema.Types.Mixed})

混合类型因为没有特定约束,因此可以任意修改,一旦修改了原型,则必须调用markModified()

person.anything = {x:[3,4,{y:'change'}]}
person.markModified('anything')  //传入anything,表示该属性类型发生变化
person.save()

ObjectId

主键,一种特殊而且非常重要的类型,每个 Schema 都会默认配置这个属性,属性名为_id,除非自己定义,方可覆盖

var mongoose = require('mongoose')
var ObjectId = mongoose.Schema.Types.ObjectId
var StudentSchema = new Schema({})   //默认会有_id:ObjectId
var TeacherSchema = new Schema({id:ObjectId})  //只有id:ObjectId

Array

Array在JavaScript编程语言中并不是数组,而是集合,因此里面可以存入不同的值,以下代码等价:

var ExampleSchema1 = new Schema({array:[]})
var ExampleSchema2 = new Schema({array:Array})
var ExampleSchema3 = new Schema({array:[Schema.Types.Mixed]})
var ExampleSchema4 = new Schema({array:[{}]})

附言

Schema不仅定义了文档结构和使用性能,还可以有扩展插件、实例方法、静态方法、复合索引、文档生命周期钩子

Schema可以定义插件,并且插件具有良好的可拔插性, Schema#add, Schema#set, Schema#static ...

Schema 扩展

实例方法

我们创造的Schema不仅要为后面的Model和Entity提供公共的属性,还要提供公共的方法。

var PersonSchema = new Schema({name:String,type:String})
//查询类似数据
PersonSchema.methods.findSimilarTypes = function(cb){
  return this.model('Person').find({type:this.type},cb)
}

var PersonModel = mongoose.model('Person',PersonSchema)
var krouky = new PersonSchema({name:'krouky',type:'前端工程师'})
krouky.findSimilarTypes(function(err,persons){
  //persons中就能查询到其他前端工程师
})

静态方法

静态方法可以在 model 层使用

  PersonSchema.statics.findByName = function(name,cb){
    this.find({name:new RegExp(name,'i'),cb})
  }
  var PersonModel = mongoose.model('Person',PersonSchema)
  PersonModel.findByName('krouky',function(err,persons){
    //找到所有名字叫krouky的人
  })

索引

索引或者复合索引能让搜索更加高效,默认索引就是主键索引ObjectId,属性名为_id,或者使用index: true 来创建索引。

虚拟属性

Schema中如果定义了虚拟属性,那么该属性将不写入数据库,例如

var PersonSchema = new Schema({
  name:{
    first:String,
    last:String
  }
})
var PersonModel = mongoose.model('Person',PersonSchema)
var krouky = new PersonModel({
  name:{first:'krouky',last:'han'}
})

全名:

console.log(krouky.name.first + ' ' + krouky.name.last);

这个时候就可以使用虚拟属性

PersonSchema.virtual('name.full').get(function(){
    return this.name.first + ' ' + this.name.last
})

那么就能用krouky.name.full来调用全名了,反之如果知道full,也可以反解firstlast属性

PersonSchema.virtual('name.full').set(function(name){
  var split = name.split(' ')
  this.name.first = split[0]
  this.name.last = split[1]
});
var PersonModel = mongoose.model('Person',PersonSchema)
var krouky = new PersonModel({})
krouky.name.full = 'krouky han'  //会被自动分解
console.log(krouky.name.first)   //krouky

配置项

在使用new Schema(config)时,我们可以追加一个参数options来配置Schema的配置,形如:

var ExampleSchema = new Schema(config,options)

或者使用

var ExampleSchema = new Schema(config)
ExampleSchema.set(option,value)

以下是官网目前提供的所有Schema.options

mongoose.Schema.options

有效的配置项

详细使用根据链接查看官方文档

上一篇 下一篇

猜你喜欢

热点阅读