mongoose 5.0 链接数据库 代码保存
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(); }) }); }
返回结果