2016-12-09 152 views
2
const express = require('express') 
const app = express() //initialised express. using express by requiring it. 
//conecting the server to browsers 
const bodyParser = require('body-parser') 
const MongoClient = require('mongodb').MongoClient 

var db 

MongoClient.connect('mongodb://aryan:[email protected]:27938/post-quotes', 
        (err, database) => { 
    console.log('inside') 
    //We move app.listen() so that it boots up only when our database is connected; ony aftert that should it flag: listening 
    if (err) return console.log(err) 

    db = database 
    app.listen(process.env.PORT || 3000, function() { 
    console.log('listening on 3000') 
}) 
    db.collection('quotes').find().toArray((err, results) => { 
     console.log(results) 
    }) 
}) 

app.use(bodyParser.urlencoded({extended: true})) 
//enabling body parser to handle formms as in our case 




app.get('/', (req, res) => { 
    res.sendFile('/media/aryan/Adani/zellwk' + '/index.html') 
}) // /index.html specifies that index.html is stored in the root of your project directory. 

app.post('/quotes', (req, res) => { 
    db.collection('quotes').save(req.body, (err, result) =>{ //creating a mongodb Collection called quotes and usiing .save silmultaneously to save it on the mongodb server 
     if (err) return console.log(err) 

     console.log("Save Successful") 
     res.redirect('/') // Now what after the user presses submit. We need to show him som echanges. So redirect him to the starting page. 

    }) 



}) 

在登錄屏幕,我得到一個錯誤:MongoError:無法連接到服務器上的第一個連接

MongoError: failed to connect to server [ds047955.mongolab.com:47955] on first connect

下面是完整的日誌:

inside { MongoError: failed to connect to server [ds127938.mlab.com:27938] on first connect at Pool. (/media/aryan/Adani/zellwk/node_modules/mongodb-core/lib/topologies/server.js:309:35) at emitOne (events.js:96:13) at Pool.emit (events.js:188:7) at Connection. (/media/aryan/Adani/zellwk/node_modules/mongodb-core/lib/connection/pool.js:270:12) at Connection.g (events.js:292:16) at emitTwo (events.js:106:13) at Connection.emit (events.js:191:7) at Socket. (/media/aryan/Adani/zellwk/node_modules/mongodb- core/lib/connection/connection.js:185:10) at Socket.g (events.js:292:16) at emitNone (events.js:86:13) name: 'MongoError', message: 'failed to connect to server [ds127938.mlab.com:27938] on first connect' }

+0

你對這個問題有什麼其他答案嗎? –

+0

不!我掃描的許多線程都沒有工作。 – Aryan

+0

到GitHub倉庫的鏈接[點擊這裏](https://github.com/MaximumEndurance/Blog-MongoDB)和錯誤日誌[點擊這裏](https://github.com/MaximumEndurance/Blog-MongoDB/blob/master/Error%20log)...感謝您的考慮。 – Aryan

回答

0

從你的錯誤信息,我假設你正在使用mlab的mongodb進行連接。

我曾遇到過這個錯誤,那是因爲我的密碼包含'@'字符。因此在更改/刪除'@'字符'後。我認爲'@'字符被mlab用來分隔連接字符串。

希望能幫助你或別人。

0

爲了將來的參考,我經常遇到這個問題,當開始一個項目功能MongoDB(使用mLab)。請記住,您首先必須先創建一個「數據庫用戶」,並將這些憑據放入連接URL中:mongodb://<dbuser>:<dbpassword>@ds11111.mlab.com:11111/your-db-name

dbuser和dbpassword不是您的mLab登錄憑據,而是您創建數據庫用戶時的憑據。我經常忘記的細微差別。

相關問題