feat(db): 优化 MongoDB 连接逻辑,移除不必要的代码并添加连接选项
This commit is contained in:
parent
0742208897
commit
ee5ec21aa3
@ -6,7 +6,6 @@ const account = process.env.MONGO_ACCOUNT
|
||||
const password = process.env.MONGO_PASSWORD
|
||||
const host = process.env.MONGO_HOST || '122.152.201.90'
|
||||
const port = process.env.MONGO_PORT || '27017'
|
||||
// const dbName = process.env.MONGO_DB_NAME || 'customer'
|
||||
|
||||
let isConnected = false
|
||||
|
||||
@ -22,36 +21,29 @@ exports.connectMongoDB = async function () {
|
||||
}
|
||||
|
||||
try {
|
||||
try {
|
||||
const mongoDBUrl = `mongodb://${account}:${password}@${host}:${port}`
|
||||
const mongoDBUrl = `mongodb://${account}:${password}@${host}:${port}`
|
||||
|
||||
// 连接 MongoDB,不再需要 useNewUrlParser 和 useUnifiedTopology
|
||||
await mongoose.connect(mongoDBUrl)
|
||||
mongoose.connect(mongoDBUrl, {
|
||||
useNewUrlParser: true,
|
||||
useUnifiedTopology: true
|
||||
})
|
||||
|
||||
const db = mongoose.connection
|
||||
mongoose.connection.on('open', () => {
|
||||
console.log('MongoDB 连接成功')
|
||||
isConnected = true
|
||||
})
|
||||
|
||||
db.once('open', () => {
|
||||
console.log('MongoDB 连接成功')
|
||||
isConnected = true
|
||||
})
|
||||
mongoose.connection.on('error', (err) => {
|
||||
console.error('MongoDB 连接错误:', err.message)
|
||||
isConnected = false
|
||||
})
|
||||
|
||||
db.on('error', (err) => {
|
||||
console.error('MongoDB 连接错误:', err.message)
|
||||
isConnected = false
|
||||
})
|
||||
|
||||
db.on('close', () => {
|
||||
console.log('MongoDB 连接关闭')
|
||||
isConnected = false
|
||||
})
|
||||
|
||||
console.log('MongoDB 连接初始化成功')
|
||||
} catch (err) {
|
||||
console.error('MongoDB 连接初始化失败:', err.message)
|
||||
throw err
|
||||
}
|
||||
mongoose.connection.on('close', () => {
|
||||
console.log('MongoDB 连接关闭')
|
||||
isConnected = false
|
||||
})
|
||||
} catch (err) {
|
||||
console.error('MongoDB 连接初始化失败:', err.message)
|
||||
throw err // 重新抛出错误,以便其他地方可以处理
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user