mongoose 是 nodejs 中连接应用与 mongodb 数据库的一个库。在 mongoose 中有几个重要的概念需要重点了解。

  • Schema: 数据库模板的描述、定义。以及数据库中的个字段的格式等定义。
  • Model: 数据库的模型,Schema 的具体实现。可以操作数据库。
  • Entity: 通过 Model 创建的具体的实例。也具有操作数据库的能力。

使用

1
2
# 安装
npm install mongoose

启动数据库

1
mongod --dbpath=path

在 js 文件中使用编写代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const mongoose = require('mongoose')

mongoose.Promise = Promise // 让 mongoose 中的 Promise 使用 node 中全局的 Promise,也可以使用其他库,例如 bluebird,http://mongoosejs.com/docs/promises.html

mongoose.set('debug', true) // 开启 debug
mongoose.connect('mongodb://localhost/test') // 连接数据库 test 为数据库名称,默认端口为 27017,如果不是这个端口需要增加端口

mongoose.connection.on('open', () => {
  console.log('mongodb opened')
})

// 创建 一个 User Schema,用来描述 User 集合的结构
const UserSchema = new mongoose.Schema({
  name: String,
  times: {
    type: Number,
    default: 0
  }
})

// 创建 model
const User = mongoose.model('User', UserSchema) // 基于 UserSchema 建模,这时会在数据库中自动创建 users 的集合,注意这里的大写的 User 会在数据库中转小写负数

// 创建具体的用户实例
;(async () => {
  // console.log(await User.find({}).exec()) // []
  // 实例化一个具体的用户
  const user = new User({
    name: 'newming'
  })
  // 保存到数据库中
  await user.save()
  // console.log(await User.find({}).exec()) // [{name: 'nemwing', times: 0}] json 格式的一条数据

  // 查找一条数据,并更新
  const user = await User.findOne({name: 'newming'})
  user.name = 'newminghaha'
  await user.save()
  // console.log(await User.find({}).exec()) // [{name: 'nemwinghaha', times: 0}]

  // 调用 Schema 静态方法
  console.log(User.getUser('newminghaha').exec())

  // 调用实例 method
  const user = await User.findOne({name: 'newminghaha'})
  const newUser = user.fetchUser('newminghaha')
  console.log(newUser)
})()

// 定义 Schema 前置钩子方法 http://mongoosejs.com/docs/api.html#schema_Schema-pre
UserSchema.pre('save', next => {
  this.times ++
  next() // 每次保存前执行
})

// 定义 Schema 静态方法 http://mongoosejs.com/docs/api.html#schema_Schema-static
UserSchema.statics = {
  async getUser(name) {
    const user = await this.findOne({
      name
    })
    return user
  }
}

// 定义 Schema 实例方法
UserSchema.methods = {
  async fetchUser(name) {
    const user = await this.model('User').findOne({
      name: name
    }).exec()
  }
}