mongoose基础教程(二) Schema与Model (更新

2018-01-12  本文已影响2066人  coolheadedY

Schema

Schema 是什么

在 Mongoose 中,所有数据都由一个 Schema 开始创建。每一个 schema 都映射到一个 Mongodb 的集合(collection),并定义了该集合(collection)中的文档(document)的形式。

定义一个Scheme

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserScehma = new Schema({
  name: { type: String, required: true },
  createTime: { type: Date, default: Date.now },
  favoriteIds: [String]
  sex: String,
  avatar: String,
  vip: Boolean,
})

new Schema({}) 中的name 称之为Schema 的键
Schema 中的每一个键都定义了一个文档(document)的一个属性。
这里我们定义:
用户名name , 它将映射为String 的Schema 类,设置required: true 规定创建文档(document)时name 必须设置。
注册时间 createTime 会被映射为 Date 的 Schema 类型,如没设置默认为Date.now 的值。
会员 vip 会被映射为 Boolean 的 Schema 类型。
收藏的id 列表被映射为 字符串 Array 的Schema 类型,['1', '2', '3']。
允许的Schema类型有:

实例方法

调用者:通过Schema 创建Model 构造出的实例
我们可以为Model 创建实例方法供Model 实例调用。

const animalSchema = new Schema({ name: String, type: String })
// 实例方法
animalSchema.methods.findSimilarTypes = async function() {
  // this 为调用此方法的Model 实例对象,此实例使用Model 方法前还需要指定model
  return this.model('Animal').findOne({ type: this.type })
}
const Animal = mongoose.model('Animal', animalSchema)
const dog = new Animal({ type: 'dog' })

dog.findSimilarTypes().then(animal => console.log(animal.name)) // woff

静态方法

调用者:通过Schema 创建的Model
我们可以为Model 创建静态方法供Model 调用。

const animalSchema = new Schema({ name: String, type: String })
// 静态方法
animalSchema.statics.findByName = async function(name) {
  return this.findOne({ name })
}

const Animal = mongoose.model('Animal', animalSchema)

Animal.findByName('tom').then(animal => console.log(animal.name)) // tom

查询助手

调用者:通过Schema 创建的Model
为Model 查询后的结果(query)设置特定方法

// 查询助手
animalSchema.query.byName = async function(name) {
  return this.find({ name })
}

const Animal = mongoose.model('Animal', animalSchema)

Animal.find().byName('tom').then(animal => console.log(animal.name)) // tom
// 先查询了所有动物,再从结果query里找到tom

索引

mongodb 每个document 都有一个_id 的主键也就是第一索引,同时也支持创建第二索引。
独立索引:
1.在定义时Schema 内创建也可用Schema.index创建。
2.根据单个field 查找时使用
组合索引:
1.由Schema.index创建。
2.当需要既要查找field1 又要查找field2 时使用
设置:
设置索引1升序索引、-1降序索引
unique: true 设置为唯一索引

const animalSchema = new Schema({
  name: { type: String, index: true }, // 独立索引
  type: String,
  numbers: { type: [String], index: true } // 独立索引
})

animalSchema.index({ name: 1, type: -1 }) // 组合索引
animalSchema.index({ type: -1 }, { unique: true }) // 降序、唯一索引

const Animal = mongoose.model('Animal', animalSchema)
创建的索引

图中是我们创建的索引,可以看出name_1_type_-1 是一个组合索引,name_1 和type_-1 也是一个独立索引。

文本索引

上一篇下一篇

猜你喜欢

热点阅读