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

347 阅读2分钟

前言

在开发途中,我们可能需要在同一个项目中链接多个不同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文档地址:mongoosejs.com/docs/migrat…