连接Node.js API 到 MongoDB



我正在尝试在Node.js上构建API-REST。我之前做了另一个,但现在我无法连接到MongoDB数据库。此数据库具有身份验证过程,但不知何故,凭据无法按预期工作。我可以用它们在本地连接到数据库,但在尝试远程连接时不能。

我读了一段时间,似乎由于一些更新,我尝试使用的连接字符串根本不起作用。下面是一些代码:

配置.js:

module.exports = {
port: process.env.PORT || XXXX,
db: process.env.MONGODB || 'mongodb://user:password@[IP adresss]:[port]/[databaseName]',
TOKEN_SECRET: process.env.TOKEN_SECRET || 'aSecretToken'
}

索引.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}`)
})
})

我知道,和往常一样,这之前可能会被问过,我想这一定是世界上最简单的事情,但我真的被这个s***困住了!

提前感谢,伙计们!

编辑:错误日志

(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.
mongoose.connect("mongodb://user:password@[IP adresss]:[port]/[databaseName]",{auth:{authdb:"admin"}}, () => {})

尝试放置该选项。

最新更新