一条小码农

努力一点,现在想要的未来都会有。

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();
     
    
    })

  });
}

返回结果

 

posted @ 2018-03-08 17:59  萝卜的博  阅读(199)  评论(0编辑  收藏  举报