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' }
你對這個問題有什麼其他答案嗎? –
不!我掃描的許多線程都沒有工作。 – Aryan
到GitHub倉庫的鏈接[點擊這裏](https://github.com/MaximumEndurance/Blog-MongoDB)和錯誤日誌[點擊這裏](https://github.com/MaximumEndurance/Blog-MongoDB/blob/master/Error%20log)...感謝您的考慮。 – Aryan