什么是Moongoose

  • Mongoose是一个文档对象模型库,它对Node原生的MongoDB模块进行了进一步的优化封装,并提供了更多的功能

优点

  1. 可以为文档创建一个模式结构Scheme
  2. 可以对模型中的对象/文档进行验证
  3. 数据可以通过类型转换转换为对象模型
  4. 可以使用中间件处理应用业务逻辑
  5. 比Node原生操作MongoDB更加简单、便捷

Mongoose的使用

连接数据库

  1. const mongoose = require('mongoose')
  2. const DB_NAME = 'student';
  3. const DB_URL = 'localhost:27017'
  4. let dbPromise = new Promise((resolve, reject) => {
  5. mongoose.connect(`mongodb://${DB_URL}/${DB_NAME}`, {useNewUrlParser: true, useUnifiedTopology: true})
  6. mongoose.connection.on('open', (err) => {
  7. if (!err) {
  8. console.log('数据库连接成功!');
  9. resolve();
  10. } else {
  11. reject(err)
  12. }
  13. });
  14. });

创建模型对象

  1. const mongoose = require('mongoose')
  2. // 1.引入约束Schema
  3. let Schema = mongoose.Schema;
  4. // 2.创建一个约束对象实例
  5. let studentSchema = new Schema({
  6. stu_no: {
  7. type: String,
  8. required: true,
  9. unique: true
  10. },
  11. name: {
  12. type: String,
  13. required: true
  14. },
  15. age: {
  16. type: Number,
  17. required: true
  18. },
  19. sex: {
  20. type: String,
  21. required: true
  22. },
  23. hobby: {
  24. type: [String]
  25. },
  26. info: {
  27. type: Schema.Types.Mixed // 接收任意类型
  28. },
  29. date: {
  30. type: Date,
  31. default: Date.now()
  32. },
  33. enable_flag: {
  34. type: String,
  35. default: 'Y'
  36. }
  37. });
  38. // 3.创建模型对象
  39. let studentModel = mongoose.model('students', studentSchema);

使用模型对象操作数据库

增加

  1. // 第一种写法
  2. dbPromise.then(() => {
  3. studentModel.create({
  4. stu_no: '2019180001',
  5. name: '哈哈',
  6. age: 18,
  7. sex: '男',
  8. hobby: ['看书', '学习'],
  9. info: 'He is a good man'
  10. }, (err, data) => {
  11. if (!err) {
  12. console.log('数据写入成功', data)
  13. } else {
  14. console.log(err)
  15. }
  16. })
  17. }).catch((err) => {
  18. console.log(err)
  19. });
  20. // 第二种写法
  21. dbPromise.then(() => {
  22. studentModel.create({
  23. stu_no: '2019180001',
  24. name: '哈哈',
  25. age: 18,
  26. sex: '男',
  27. hobby: ['看书', '学习'],
  28. info: 'He is a good man'
  29. }, (err, data) => {
  30. if (!err) {
  31. console.log('数据写入成功', data)
  32. } else {
  33. console.log(err)
  34. }
  35. })
  36. }, (err) => {
  37. console.log(err)
  38. })
  39. // 第三种写法
  40. (async () => {
  41. await dbPromise;
  42. studentModel.create({
  43. stu_no: '2019180001',
  44. name: '哈哈',
  45. age: 18,
  46. sex: '男',
  47. hobby: ['看书', '学习'],
  48. info: 'He is a good man'
  49. }, (err, data) => {
  50. if (!err) {
  51. console.log('数据写入成功', data)
  52. } else {
  53. console.log(err)
  54. }
  55. })
  56. })()

删除

  1. dbPromise.then(() => {
  2. studentModel.deleteOne({ // 或者deleteMany
  3. stu_no: '2019180001'
  4. }, (err, data) => {
  5. if (!err) {
  6. console.log(data)
  7. } else {
  8. console.log(err)
  9. }
  10. })
  11. }).catch((err) => {
  12. console.log(err)
  13. });

修改

  1. dbPromise.then(() => {
  2. studentModel.updateOne({ // 或者upodateMany
  3. stu_no: '2019180001'
  4. },{age: 28}, (err, data) => {
  5. if (!err) {
  6. console.log(data)
  7. } else {
  8. console.log(err)
  9. }
  10. })
  11. }).catch((err) => {
  12. console.log(err)
  13. });

查询

  1. dbPromise.then(() => {
  2. studentModel.find({
  3. stu_no: '2019180001'
  4. }, (err, data) => {
  5. if (!err) {
  6. console.log(data)
  7. } else {
  8. console.log(err)
  9. }
  10. })
  11. }).catch((err) => {
  12. console.log(err)
  13. });