我想在Node.js上構建一個API-REST。我之前做了另一個,但現在我無法連接到MongoDB數據庫。這個數據庫有一個auth進程,但不知何故,憑據不能按預期工作。我可以用它們在本地連接到數據庫,但在嘗試遠程連接時不能連接到數據庫。連接到MongoDB的Node.js API
我讀了一會兒,看來,由於一些更新,我試圖使用的連接字符串根本不起作用。下面是一些代碼:
config.js:
module.exports = {
port: process.env.PORT || XXXX,
db: process.env.MONGODB || 'mongodb://user:[email protected][IP adresss]:[port]/[databaseName]',
TOKEN_SECRET: process.env.TOKEN_SECRET || 'aSecretToken'
}
index.js:
'use strict'
const mongoose = require('mongoose')
const app = require('./app')
const config = require ('./config')
mongoose.Promise = global.Promise;
mongoose.connect(config.db, (err,res) => {
if(err){
return console.log(`Error when connecting database: ${err}`)
}
console.log('Connection to Mongo database successful...')
app.listen(config.port,() => {
console.log(`API REST running on [IP Adress]:${config.port}`)
})
})
我知道,一如既往,這可能會被問過,我想那一定是世界上最簡單的事情,但我真的堅持這個***!
在此先感謝,夥計們!
編輯:錯誤日誌
(node:3169) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/connections.html#use-mongo-client
Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.
Error when connecting database: MongoError: Authentication failed.
(node:3169) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: Authentication failed.
請顯示您的錯誤日誌 – ZeroCho
對不起,我完全忘記了!它已經被添加到問題中。 – camnuel
這很難診斷。該錯誤非常普遍。你確定你把正確的ID,密碼,主機,數據庫名?另外,請檢查該端口是否可訪問。 – ZeroCho