
在复杂的应用场景中,我们可能需要连接并操作多个mongodb数据库。mongoose提供了两种主要的方式来建立数据库连接:mongoose.connect() 和 mongoose.createconnection()。前者通常用于建立应用程序的默认连接,而后者则允许你创建独立的、非默认的连接实例,这对于操作多个数据库或为不同模块使用不同数据库连接的场景至关重要。
当使用 mongoose.createConnection() 方法时,它会返回一个全新的 Connection 实例。这个实例独立于全局的 mongoose 对象。这意味着,通过这个连接实例注册的模型,将仅与这个特定的连接绑定,而不是全局的 mongoose 对象。
错误根源分析:
在原始问题中,用户尝试通过 conn.model('Price', priceSchema); 将 Price 模型注册到 conn 这个连接实例上。这是正确的做法。然而,在尝试实例化模型时,却使用了 new conn.Price();。这里的错误在于,conn.Price 并不是 Mongoose 提供的一种直接访问已注册模型构造函数的方式。conn 对象本身不会动态地将已注册的模型作为其属性暴露出来。
要正确地获取并使用通过 conn.model() 注册的模型构造函数,你需要:
下面是一个详细的示例,展示了如何使用 mongoose.createConnection() 建立多个数据库连接,并正确地定义、注册和实例化模型:
const mongoose = require('mongoose');
// 数据库连接选项
// 注意:useCreateIndex, useFindAndModify 在 Mongoose 6.0+ 中已弃用,
// useNewUrlParser, useUnifiedTopology 也是默认行为,通常不再需要显式设置。
const connectionOptions = {
useNewUrlParser: true, // 保持兼容性,尽管在新版本中已是默认
useUnifiedTopology: true // 保持兼容性,尽管在新版本中已是默认
};
// --- 连接到第一个数据库:db_en ---
const dbEnConn = mongoose.createConnection("mongodb://localhost/db_en", connectionOptions);
// 监听连接事件,确保连接成功或处理错误
dbEnConn.on('connected', () => {
console.log('成功连接到数据库:db_en');
});
dbEnConn.on('error', (err) => {
console.error('db_en 数据库连接错误:', err);
});
dbEnConn.on('disconnected', () => {
console.log('db_en 数据库连接已断开');
});
// 定义 Price 模型的 Schema
const priceSchema = new mongoose.Schema({
fixed: {
1: { type: Number, default: 199 },
3: { type: Number, default: 499 },
6: { type: Number, default: 729 },
12: { type: Number, default: 999 }
}
}, { timestamps: true }); // 添加时间戳,便于追踪
// 将 Price 模型注册到 dbEnConn 连接实例上,并获取其构造函数
const PriceModel = dbEnConn.model('Price', priceSchema);
// 实例化 Price 模型并保存数据
async function savePriceData() {
try {
const newPriceEntry = new PriceModel({
fixed: {
1: 200,
3: 500
}
});
const savedPrice = await newPriceEntry.save();
console.log('价格数据已成功保存到 db_en:', savedPrice);
} catch (error) {
console.error('保存价格数据时发生错误:', error);
}
}
// --- 连接到第二个数据库:db_another ---
const dbAnotherConn = mongoose.createConnection("mongodb://localhost/db_another", connectionOptions);
// 监听连接事件
dbAnotherConn.on('connected', () => {
console.log('成功连接到数据库:db_another');
});
dbAnotherConn.on('error', (err) => {
console.error('db_another 数据库连接错误:', err);
});
dbAnotherConn.on('disconnected', () => {
console.log('db_another 数据库连接已断开');
});
// 定义 User 模型的 Schema
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true }
}, { timestamps: true });
// 将 User 模型注册到 dbAnotherConn 连接实例上,并获取其构造函数
const UserModel = dbAnotherConn.model('User', userSchema);
// 实例化 User 模型并保存数据
async function saveUserData() {
try {
const newUserEntry = new UserModel({
name: 'Alice',
email: 'alice@example.com'
});
const savedUser = await newUserEntry.save();
console.log('用户数据已成功保存到 db_another:', savedUser);
// 尝试保存第二个用户,演示错误处理(如 email unique 约束)
const anotherUser = new UserModel({
name: 'Bob',
email: 'alice@example.com' // 会导致唯一性约束错误
});
await anotherUser.save();
} catch (error) {
// Mongoose 错误通常有 name 和 code 属性
if (error.code === 11000) {
console.error('保存用户数据时发生错误: 邮箱已存在。', error.message);
} else {
console.error('保存用户数据时发生错误:', error);
}
}
}
// 运行示例
async function runExamples() {
await savePriceData();
await saveUserData();
// 在实际应用中,你可能需要等待所有操作完成后再关闭连接
// setTimeout(() => {
// dbEnConn.close(() => console.log('db_en 连接已关闭'));
// dbAnotherConn.close(() => console.log('db_another 连接已关闭'));
// }, 5000); // 示例:5秒后关闭
}
runExamples();通过遵循这些指南,你将能够有效地在 Mongoose 中管理和使用多个数据库连接及其对应的模型,从而构建健壮且可扩展的 Node.js 应用。
以上就是Mongoose多数据库连接与模型使用指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号