Mongoose多数据库连接及实用样例

使用环境:

MongoDB 3.6

插件版本:

"mongodb": "^3.1.10",
"mongoose": "^5.4.2",

直接上代码

let mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.set('debug', true);
let dbname1 = 'datab1';
let dbname2 = 'datab2';
const options = {
    useNewUrlParser: true,
    useCreateIndex: true,
    reconnectTries: Number.MAX_VALUE
};
let uri_1 = 'mongodb://username:[email protected]:27017/'+dbname1;
let uri_2 = 'mongodb://192.168.0.2:27017/'+dbname2;
let db1  = mongoose.createConnection(uri_1, options);
db1.on('error', () => {
    console.log(uri_1+"\r\n数据库[" + dbname1 + "]连接错误!" + error);
}).on('connected', () => {
    console.log(uri_1+"\r\n数据库[" + dbname1 + "]连接成功!");
});
let db2  = mongoose.createConnection(uri_2, options);
db2.on('error', () => {
    console.log(uri_2+"\r\n数据库[" + dbname2 + "]连接错误!" + error);
}).on('connected', () => {
    console.log(uri_2+"\r\n数据库[" + dbname2 + "]连接成功!");
});

定义好后接下来上Model测试

let InfoC_Schema = new mongoose.Schema({
    status: {type:Number, default: 0},                 
    desc: String,                                       
    url: String,                                        
    readtime: Date,                                     
    createdate: {type:Date, default: Date.now}
}, {
    versionKey: false,
    collection: "cx_infoc"
});
let InfoC = db1.model("InfoC", InfoC_Schema);

let Logs_Schema = new mongoose.Schema({
    objname: String,                                
    objid: String,                                  
    desc: String,                                   
    level:{type:Number, default: 1},                
    createdate: {type:Date, default: Date.now}
}, {
    versionKey: false,
    collection: "cx_logs"
});
let Logs = db2.model("Logs", Logs_Schema);


InfoC.find({}, function(err, list){
    console.log("db1.>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
   console.log(list);
});

Logs.find({}, function(err, list){
    console.log("db2.>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    console.log(list);
});

 

你可能感兴趣的:(Mongoose多数据库连接及实用样例)