• 同一项目如何连接多个mongo服务器地址


    前言

    在开发途中,我们可能需要在同一个项目中链接多个不同mongo服务器地址或者同一个mongo服务器地址下不同集合!此时采用mongoose.connect链接是不行的!
    这时候,你需要使用mongoose.createConnection方法进行连接数据库!
    以下,我将使用一个例子来向大家讲述这个方法。这个方法中,不同的mongo集合,我使用了同一套Schema;

    1. 连接不同的数据库/集合

    由于在mongoose中,链接之后,会形成一个自身的mongo实例集合,所以我们需要把想要的Schema挂到对应的mongo实例上;

    /models/db_one.js

    const mongoose = require('mongoose');
    //链接本地test_one集合 mongodb://localhost/test_one 
    let dbOne = mongoose.createConnection(`mongodb://localhost/test_one`);
    dbOne.on('err', function () {
      console.log('dbOne:连接数据库失败');
    });
    dbOne.once('open', function () {
      console.log('dbOne:连接数据库成功');
    });
    
    //导入Schema
    dbOne.model('User', require('./schemas/user'));
    
    //导出
    module.exports = dbOne;
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    /models/db_two.js

    const mongoose = require('mongoose');
    //链接线上阿里云test2集合 mongodb://localhost/test_one
    /**
     * name 数据库服务器登陆账号 
     * password 数据库服务器登陆密码
     * ip 服务器ip
     */
    let dbTwo = mongoose.createConnection(`mongodb://${name}:${password}@${ip}:27017/test2?authSource=admin`);
    dbTwo.on('err', function () {
      console.log('dbTwo:连接数据库失败');
    });
    dbTwo.once('open', function () {
      console.log('dbTwo:连接数据库成功');
    });
    
    //导入Schema
    dbTwo.model('User', require('./schemas/user'));
    
    //导出
    module.exports = dbTwo;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    /models/db_three.js

    const mongoose = require('mongoose');
    //链接本地test_three集合 mongodb://localhost/test_three 
    let dbThree = mongoose.createConnection(`mongodb://localhost/test_three`);
    dbThree.on('err', function () {
      console.log('dbThree:连接数据库失败');
    });
    dbThree.once('open', function () {
      console.log('dbThree:连接数据库成功');
    });
    
    //导入Schema
    dbThree.model('User', require('./schemas/user'));
    
    //导出
    module.exports = dbThree;
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    写一个Schema
    /models/schemas/user.js

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    const User = new Schema({
      name: {
        type: String,
        index: true,
        default: null
      },
      age: {
        type: Number,
        default: 0
      },
      register_time: {
        type: Date,
        default: Date.now()
      },
      remark: {
        type: String,
        default: null
      },
      vip: {
        type: Boolean,
        default: false
      },
      address: {
        type: String,
        default: null
      }
    });
    // 添加伙伴
    User.statics.add = function (data) {
      return this.create(data);
    };
    
    module.exports = User;
    
    
    • 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

    以上:
    db_one与db_two属于链接不同的mongo服务器地址;
    db_one与db_three属于链接同一个的mongo服务器地址的不同集合;

    2. 使用

    实际使用mongo方法如下:

    let express = require('express');
    let router = express.Router();
    //引入相关mongo
    let dbOne = require('../models/db_one');
    let dbTwo = require('../models/db_two');
    let dbThree = require('../models/db_three');
    router.post('/', async function (req, res, next) {
      try {
        let { type, name } = req.body;
        let data = { name, age: 10 };
        //根据不同的type,向不同的数据库写入数据
        if (type === '1') {
          //dbOne为mongo实例,所以需要使用dbOne.models获取到当前实例的models集合;
          //使用dbOne.models.具体某个model,获取所需要的model,之后的model静态方法可以以正常操作使用;
          await dbOne.models.User.add(data);
        } else if (type === '2') {
          await dbTwo.models.User.add(data);
        } else if (type === '3') {
          await dbThree.models.User.add(data);
        }
        return res.json({ code: '200', message: '成功' });
      } catch (error) {
        return res.json({ code: '500', message: '失败' });
      }
    });
    
    module.exports = router;
    
    
    • 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

    3. 结语

    链接不同的数据库,如果需要,可以自行优化,比如,链接地址配置化、将多个链接合并到同一个方法中输出,便于扩展和后续维护;

    mongoose文档地址:https://mongoosejs.com/docs/migrating_to_6.html

  • 相关阅读:
    C语言--从键盘输入10个数字放在数组中,并输出
    SP11 FCTRL - Factorial
    idea启动非maven javaWeb项目,idea打包非maven javaWeb项目
    前后端分离
    经常散步好不好?60以上老人3个好处收入囊中,但有3点要注意
    【经济调度】基于蝙蝠算法实现电力系统经济调度附Matlab代码
    GPT总设计师:大型语言模型的未来
    【笔记】逻辑斯蒂回归
    keepalived的通信原理
    【通信】Matlab实现多同步压缩变换
  • 原文地址:https://blog.csdn.net/Long861774/article/details/125910187