一、简介

NodeJs 环境下对 MongoDB 进行便捷操作的对象建模工具

二、安装

  1. $ npm install mongoose

三、建立连接

  1. // config/db.js
  2. // 1. 引入 mongoose
  3. const mongoose = require('mongoose')
  4. // 2. 定义连接的地址
  5. // 协议是特定的 mongodb
  6. // hello 指具体的数据库名字
  7. const url = 'mongodb://localhost:27017/hello'
  8. // 3. 连接
  9. mongoose
  10. .connect(url)
  11. .then(() => {
  12. console.log('数据库连接成功~')
  13. })
  14. .catch((error) => {
  15. console.log('数据库连接失败!!!')
  16. console.log(error.message)
  17. })
  18. // 4. 不要忘了暴露
  19. module.exports = mongoose

四、针对不同的集合(collection)来建模

1. 将所有的模型文件都统一放置在项目的某个目录下。(这里选择 models 目录)

2. 创建模型文件,文件名建议使用集合名字的单数形式。

比如:

  1. user.js 指 users 集合
  2. good.js 指 goods 集合

3. 定义 Schema

Mongoose 的一切始于 Schema。每个 schema 都会映射到一个 MongoDB collection,并定义这个 collection 文档的构成。

  1. // models/cat.js
  2. // 1. 引入已经连接了 MongoDB 的 Mongoose
  3. const mongoose = require('../config/db.js')
  4. // 2. 定义 Schema
  5. const catSchema = new mongoose.Schema({
  6. // key -> 字段名
  7. // value -> 类型
  8. name: String, // 喵咪姓名
  9. age: Number, // 喵咪年龄
  10. master: { // 主人
  11. type: String
  12. },
  13. })
  14. /**
  15. * 3. 实例方法 (可选的)
  16. * 不会喵怎么算喵星人, 现在给猫咪 document 加个 "speak" 方法
  17. *
  18. * 注意:
  19. * 1. 不要使用箭头函数,不然 this 指向会出问题。
  20. * 2. 加在 schema methods 属性的函数会编译到 Model 的 prototype,
  21. * 也会暴露到每个 document 实例
  22. */
  23. catSchema.methods.speak = function() {
  24. console.log(`
  25. (>^ω^<)喵,我是 ${this.master} 家的 ${this.name}
  26. `)
  27. }

4. 创建 模型

基于 定义好的 schema 来创建 模型。使用 mongoose.model(modelName, schema) 函数

注意:集合的名字是 modelName 的复数形式,这里 modelName 使用 **cat 。那么对应的 collection 名字是 cats**

  1. // models/cat.js
  2. // 接第三步
  3. // 4. 创建 模型。(是一个类(构造函数),推荐首字母大写)
  4. const CatModel = mongoose.model('cat', catSchema)
  5. // 5. 不要忘了暴露模型
  6. module.exports = CatModel

五、提供接口来CURD

Model 方法与 Model 实例方法

  1. // routes/cats.js
  2. // 1. 引入 express
  3. const express = require('express')
  4. // 2. 引入 需要使用的 模型文件
  5. const CatModel = require('../models/cat.js')
  6. // 3. 实例化 express.Router 的实例
  7. const router = express.Router()
  8. /**
  9. * 查询所有的猫咪
  10. * GET http://localhost:3000/cats
  11. */
  12. router.get('/', (req, res) => {
  13. // 使用静态方法 Model.find()
  14. CatModel
  15. .find()
  16. .then((data) => {
  17. // data 就是查询出的 猫咪数组
  18. // 给客户端响应
  19. res.send({
  20. code: 0,
  21. msg: '查询成功',
  22. data
  23. })
  24. })
  25. .catch((error) => {
  26. // 将错误信息输出一下,方便后续排查问题
  27. console.log(error.message)
  28. // 给客户端响应
  29. res.send({
  30. code: -1,
  31. msg: '查询失败'
  32. })
  33. })
  34. })
  35. /**
  36. * 新创建一只猫咪,使用 Model.create()
  37. * POST http://localhost:3000/cats
  38. */
  39. router.post('/', (req, res) => {
  40. // 1. 获取客户端传递过来的猫咪信息
  41. const { name, age, master } = req.body
  42. // 2. Model.create()
  43. CatModel
  44. .create({ name, age, master })
  45. .then(() => {
  46. res.send({
  47. code: 0,
  48. msg: '创建成功'
  49. })
  50. })
  51. .catch((error) => {
  52. console.log(error.message)
  53. res.send({
  54. code: -1,
  55. msg: '创建失败'
  56. })
  57. })
  58. })
  59. /**
  60. * 删除某个猫咪
  61. * DELETE http://localhost:3000/cats/:catId
  62. */
  63. router.delete('/:catId', (req, res) => {
  64. // 1. 获取要删除的猫咪的id
  65. // const id = req.params.catId
  66. const { catId } = req.params
  67. // 2. 使用 Model.deleteOne(删除条件)
  68. CatModel
  69. .deleteOne({ _id: catId })
  70. .then(() => {
  71. res.send({
  72. code: 0,
  73. msg: '删除成功'
  74. })
  75. })
  76. .catch((error) => {
  77. console.log(error.message)
  78. res.send({
  79. code: -1,
  80. msg: '删除失败'
  81. })
  82. })
  83. })
  84. /**
  85. * 修改某个猫咪的年龄
  86. * PUT http://localhost:3000/cats/:catId
  87. */
  88. router.put('/:catId', (req, res) => {
  89. // 1. 获取要修改年龄的猫咪的Id
  90. const { catId } = req.params
  91. // 2. 获取要修改成的年龄 请求体传递过来
  92. const { age } = req.body
  93. // 3. Model.updateOne(修改的条件, 修改的内容)
  94. CatModel
  95. .updateOne({ _id: catId }, { age: age })
  96. .then(() => {
  97. res.send({
  98. code: 0,
  99. msg: '修改成功'
  100. })
  101. })
  102. .catch((error) => {
  103. console.log(error.message)
  104. res.send({
  105. code: -1,
  106. msg: '修改失败'
  107. })
  108. })
  109. })
  110. // end. 不要忘了暴露 router
  111. module.exports = router
  1. // index.js
  2. // 1. 引入 express
  3. const express = require('express')
  4. // 2. 引入拆分出去的路由文件
  5. const catRouter = require('./routes/cats.js')
  6. // 3. 生成 express 实例
  7. const app = express()
  8. // 4. 一些中间件调用
  9. app.use(express.json())
  10. app.use(express.urlencoded({ extended: true }))
  11. // 5. 调用路由中间件
  12. app.use('/cats', catRouter)
  13. // end 监听端口
  14. app.listen(3000, () => {
  15. console.log('服务启动成功')
  16. })