mongoose基础教程 Schema与Model

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类型有:

  • String
  • Number
  • Date
  • Buffer
  • Boolean
  • Mixed
  • ObjectId
  • Array

实例方法

调用者:通过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 也是一个独立索引。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
mongoose中的Schema是一种用来定义MongoDB数据库中文档结构的对象。它提供了一种基于模式的方式来创建和验证数据的结构,类似于传统关系型数据库中的表结构定义。 通过使用mongoose.Schema()构造函数可以创建一个新的Schema对象。Schema对象包含字段和字段类型的定义,以及可选的验证规则和默认值。在创建Schema对象时,可以使用多种字段类型,如String、Number、Date、Boolean等,还可以定义嵌套字段、数组和引用其他模型等。 通过定义Schema,可以确保MongoDB中存储的数据符合预期的结构和类型。在创建模型时,将Schema作为参数传递给mongoose.model()函数,从而创建与该模型关联的集合,并且对该集合中的文档进行增删改查操作。 以下是一个简单的示例,展示了如何使用mongoose中的Schema: ```javascript const mongoose = require('mongoose'); const { Schema } = mongoose; // 定义用户模式 const userSchema = new Schema({ name: String, age: Number, email: { type: String, required: true, unique: true, }, }); // 创建用户模型 const User = mongoose.model('User', userSchema); // 使用用户模型进行文档操作 const user = new User({ name: 'John', age: 25, email: '[email protected]', }); user.save() .then(() => console.log('User created')) .catch((error) => console.log(error)); ``` 在上面的示例中,我们定义了一个名为userSchemaSchema对象,它包含了name、age和email字段的定义。email字段使用了一些验证规则,要求是必填字段且唯一。通过mongoose.model()函数创建User模型,并使用该模型创建了一个新的用户文档,并将其保存到数据库中。 这只是一个简单的示例,mongooseSchema功能非常强大,可以进行更复杂的模式定义和数据验证。详细的文档可以参考mongoose官方文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值