执行代码前截图
server.js
const mongoose = require("mongoose");
// 通过 createConnection 连接多个数据库
var conn1 = mongoose.createConnection("mongodb://127.0.0.1:27017/wx");
var conn2 = mongoose.createConnection("mongodb://127.0.0.1:27017/test");
var Schema = mongoose.Schema;
var schema1 = new Schema({ name: String });
var model1 = conn1.model('model1', schema1); // 会在 wx数据库 中自动创建名为 model1 的表
var schema2 = new Schema({ name: String });
var model2 = conn2.model('model2', schema2); // 会在 test数据库 中自动创建名为 model2 的表
const newModel1 = new model1({
name: '第一个数据库连接成功并写入数据'
});
newModel1.save().then(res => {
console.log("1 sucess")
}).catch (err => {
console.log("1 fail")
})
const newModel2 = new model2({
name: '第二个数据库连接成功并写入数据'
});
newModel2.save().then(res => {
console.log("2 sucess")
}).catch (err => {
console.log("2 fail")
})
执行代码后截图
参考文档 mongoose多个连接
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有