const mongoose = require('mongoose');
const dbSrc = 'mongodb://localhost/douban-trailer'
mongoose.Promise = global.Promise;
exports.connect = () => {
let maxConnectTimes = 0;
return new Promise((resolve, reject) => {
if (process.env.NODE_ENV != 'production') {
mongoose.set('debug', true)
}
mongoose.connect(dbSrc)
var db = mongoose.connection;
//监听相关事件
db.on('disconnected', () => {
maxConnectTimes++;
if(maxConnectTimes<5){
mongoose.connect(dbSrc)
}else{
throw new Error('数据库无法连接!')
}
})
db.on('error', err => {
maxConnectTimes++;
if(maxConnectTimes<5){
mongoose.connect(dbSrc)
}else{
throw new Error('数据库无法连接!')
}
})
db.once('open', () => {
console.log('MongoDB Connected successfully')
var schema = new mongoose.Schema({ name: 'string', size: 'string' });
var Tank = mongoose.model('Tank', schema);
const tank = new Tank({name:'测试数据',size:'210'})
tank.save().then(()=>{
console.log('存储正常')
})
resolve();
})
});
}
返回结果


本文详细介绍了如何使用Node.js的Mongoose库连接MongoDB数据库并进行数据存储操作。通过设置数据库连接参数,监听数据库连接状态,实现了自动重连机制,并演示了数据模型定义及数据保存过程。
4万+

被折叠的 条评论
为什么被折叠?



