2014-12-31 64 views
0

代碼的Sample-無法連接到數據庫mongolab

const express=require('express'), 
    http=require('http'), 
    handlebars=require('express-handlebars').create({defaultLayout:'main'}), 
    fs=require('fs'), 
    mongoose=require('mongoose'), 
    uriUtil = require('mongodb-uri'), 
    credentials=require('./credentials.js'), 
    bodyParser=require('body-parser'); 

    //connect to databse 
    var mongooptions = { 
     server: { 
      poolSize:5, 
      socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } }, 
      replset: { socketOptions: { keepAlive: 1, connectTimeoutMS : 30000 } 
     }, 
    }; 
    var mongodbUri=("mongodb://user:[email protected]:29831/project"); 
    var mongooseUri=uriUtil.formatMongoose(mongodbUri); 
    mongoose.connect(mongooseUri,mongooptions); 
    var conn=mongoose.connection; 
    conn.on('error',function(err){ 
     console.log(err.message); 
    }); 

    conn.on('connection',function() { 
     var app=express(); 
     app.set('port',process.env.PORT); 
     app.engine('handlebars',handlebars.engine); 
     app.set('view engine','handlebars'); 
     app.use(express.static('./public')); 
     app.use(bodyParser.json()); 
     app.use(bodyParser.urlencoded({extended: true})); 
     app.use(require('express-session')({ 
      secret: 'intro skill', 
      resave: false, 
      saveUninitialized: false, 
      cookie: {maxAge:900000} 
     })); 
     var userSchema=new mongoose.Schema({ 
      username: String, 
      password: String, 
      email : String 
     }); 
     var user=mongoose.model('users',userSchema); 
     //routing 

     function startServer(){ 
      http.createServer(app).listen(app.get('port'),function(){ 
       console.log("Server Started at port "+app.get('port')); 
      }); 
     } 

     if(require.main===module){ 
      startServer(); 
     } 
     else{ 
      module.exports=startServer; 
     } 

    }); 

這是我的node.js中的代碼我使用mongolab作爲mongodb。
我在雲9上運行應用程序。
當我使用貓鼬連接到數據庫時,它會拋出錯誤,因爲未能連接到1%40ds029831.mongolab.com:29831
應用程序正在連接到mongolab並進行身份驗證(這是成功的)後,它顯示此錯誤。 請幫我這個。

回答

3

您的密碼是否包含'@'字符?如果是,請將其替換爲%40並再次嘗試,'@'字符只應出現在主機名之前。

+0

謝謝你的工作:) – user189750

+0

太棒了。謝謝兄弟 –

+0

你先生是天才。非常感謝。我一直試圖找出最後4個小時,但沒有運氣。很高興我發現這個答案:) –