• Mongoose【node.js的优雅mongodb对象建模】


    Mongoose基础运行流程:

    官方 Docs 地址

    Mongoose 官方文档

    1. 安装:

    npm install mongoose --save
    
    • 1

    2. 使用:

    2.1 目录结构:

    在这里插入图片描述

    • config文件夹-index.js:集中存放配置信息;

      示例:

      const DB_URL = 'mongodb://localhost:27017/admin';
      exports.DB_URL = DB_URL;
      
      • 1
      • 2
    • model: mongoose Model users.js 即表示数据库users表;


    2.2 初始化连接实例 [ 创建 DBHelper.js ]


    2.2.1 链接地址书写格式[ mongoose.connect(参数格式 )]:

    不含校验:mongodb://域名:端口/数据库名称

    mongoose.connect('mongodb://localhost:27017/test');
    
    • 1

    含校验:mongodb://用户名:密码@域名:端口/数据库名称

    mongoose.connect('mongodb://user:password@localhost:27017/test')
    
    • 1

    2.2.2 完整DBHelper.js

    const mongoose = require('mongoose');
    
    const config = require('./index');
    const { DB_URL } = config;
    
    /* 
        捕捉建立初始连接时的错误 
        注意:两种错误捕捉注意区分,避免遗漏
        	1. 捕捉建立初始连接时的错误 
        	2. 捕捉建立初始连接[ 后 ]的错误;
    */
    async function main() {
        await mongoose.connect(DB_URL);
    
        // use `await mongoose.connect('mongodb://user:password@localhost:27017/test');` if your database has auth enabled
    }
    main().catch(err => console.log(err));
    
    /* 
        监测连接成功
    */
    mongoose.connection.on('connected', () => {
        console.log('连接成功')
    });
    /* 
        捕捉建立初始连接[ 后 ]的错误;
    */
    mongoose.connection.on('error', err => {
        logInfo(err, 'error');
    });
    /* 
        监测断开链接
    */
    mongoose.connection.on('disconnected', back => {
        logInfo(back, 'disconnected');
    });
    
    const logInfo = (err, which) => {
        console.log(err + '-' + which)
    }
    
    exports.mongoose = mongoose;
    
    • 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

    附:connection事件种类

    mongoose.connection事件 - Connection Events

    • connecting: Emitted when Mongoose starts making its initial connection to the MongoDB server
    • connected: Emitted when Mongoose successfully makes its initial connection to the MongoDB server, or when Mongoose reconnects after losing connectivity. May be emitted multiple times if Mongoose loses connectivity.
    • open: Emitted after 'connected' and onOpen is executed on all of this connection’s models.
    • disconnecting: Your app called Connection#close() to disconnect from MongoDB
    • disconnected: Emitted when Mongoose lost connection to the MongoDB server. This event may be due to your code explicitly closing the connection, the database server crashing, or network connectivity issues.
    • close: Emitted after Connection#close() successfully closes the connection. If you call conn.close(), you’ll get both a ‘disconnected’ event and a ‘close’ event.
    • reconnected: Emitted if Mongoose lost connectivity to MongoDB and successfully reconnected. Mongoose attempts to automatically reconnect when it loses connection to the database.
    • error: Emitted if an error occurs on a connection, like a parseError due to malformed data or a payload larger than 16MB.
    • fullsetup: Emitted when you’re connecting to a replica set and Mongoose has successfully connected to the primary and at least one secondary.
    • all: Emitted when you’re connecting to a replica set and Mongoose has successfully connected to all servers specified in your connection string.

    2.3 创建Model

    2.3.1 注意事项:

    (1): Model的使用基于Schema [ 先定义Schema ]
    const schema = new mongoose.Schema({ name: 'string', size: 'string' });
    const Tank = mongoose.model('Tank', schema);
    
    • 1
    • 2
    (2): Mongoose Model预设默认行为!!

    【注意!!】第一个参数是模型所针对的集合的单数名称。Mongoose会自动查找型号名称的复数小写版本。因此,对于上面的示例,模型Tank用于数据库中的 tanks

    const schema = new mongoose.Schema({ name: 'string', size: 'string' });
    const Tank = mongoose.model('Tank', schema);
    
    • 1
    • 2
    (3): 解决(2)中的Modle预设默认行为
    1. 阻止mongoose多元化行为 : mongoose.pluralize(null)

      mongoose 版本>5?

      mongoose.pluralize(null)
      
      • 1
    2. 基于改变Schema:

      在Scehema中声明collection:

      那么,基于此Schema的Modle的使用会基于collection参数值,

      var schema = new Schema({ name: String }, { collection: 'actor' });
      var M = mongoose.model('Actor', schema);
      // 此时 M 对应数据库中的actor ,而非mongoose预设行为中对应的actors!!
      
      
      • 1
      • 2
      • 3
      • 4
    3. 基于改变Model:

      var M = mongoose.model('Actor', schema, 'actor');
      // 此时 M 对应数据库中的actor ,而非mongoose预设行为中对应的actors!!
      
      • 1
      • 2

    2.3.2 完整users.js

    const { mongoose } = require('../config/DBHelper')
    
    const Schema = mongoose.Schema;
    
    const UsersSchema = new Schema({
        'name': String,
        'age': Number,
        'gender': String
    })
    
    /* 
        默认添加 第1参数复数名称的表;除非指定第3参数:数据库表名
    */
    const Users_Model = mongoose.model('user', UsersSchema, 'user');
    
    
    const add = async (params) => {
        const addResult = await new Users_Model(params).save();
        console.log(addResult, 'Users_Model-addResult')
    }
    
    
    const find = async (params) => {
        const findResult = await Users_Model.find(params);
        console.log(findResult, 'Users_Model-findResult')
    }
    
    const updateOne = async (query, data) => {
        const updateOneResult = await Users_Model.updateOne(query, data);
        console.log(updateOneResult, 'Users_Model-updateOneResult')
    }
    
    const deleteOne = async (query) => {
        const deleteOneResult = await Users_Model.deleteOne(query);
        console.log(deleteOneResult, 'Users_Model-deleteOneResult')
    }
    
    
    
    exports.Add_Users = add;
    
    exports.Find_Users = find;
    
    exports.UpdateOne_User = updateOne;
    
    module.exports = {
        DeleteOne_User: deleteOne,
        Add_Users: add,
        Find_Users: find,
        UpdateOne_User: updateOne
    }
    
    
    • 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

    2.4 对应 Model 操作对应数据库表内容 [ 基于 2.2 , 2.3]

    一个 Model 对应数据库一个表;

    示例:针对users表使用封装好的方法[users.js]进行操作;

    const { Add_Users, Find_Users, UpdateOne_User, DeleteOne_User } = require('./model/users')
    
    
    Add_Users({
      name: '绿萝南',
      age: 12,
      gender: '男'
    })
    
    Find_Users();
    
    UpdateOne_User({ name: 'baidu.com' }, { name: '南南', age: 88 })
    
    DeleteOne_User({name:'绿萝南'})
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
  • 相关阅读:
    (229)Verilog HDL:与运算
    Git(二)版本控制、发展历史、初始化配置、别名
    手把手教你分析MySQL查询性能瓶颈,包教包会
    基于强化学习的空域作战辅助决策(1D)
    Libuv的安装及运行使用
    【rust】12、编译为 linux x86 目标
    标准C库IO函数和Linux系统IO函数
    Hive主要介绍
    基于springboot实现财务管理系统项目【项目源码+论文说明】计算机毕业设计
    更快更稳更安全!天翼云CDN了解一下
  • 原文地址:https://blog.csdn.net/weixin_43101443/article/details/128189116