同一项目如何连接多个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;

/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;

/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;

写一个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;

以上:
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;

3. 结语

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

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乾复道

与君共勉

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值