2017-08-21 140 views
0

我想在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. 
+0

请显示您的错误日志 – ZeroCho

+0

对不起,我完全忘记了!它已经被添加到问题中。 – camnuel

+0

这很难诊断。该错误非常普遍。你确定你把正确的ID,密码,主机,数据库名?另外,请检查该端口是否可访问。 – ZeroCho

回答

1
mongoose.connect("mongodb://user:[email protected][IP adresss]:[port]/[databaseName]",{auth:{authdb:"admin"}},() => {}) 

尝试把该选项。

+0

它不工作,或者我不知道如何使它工作=(任何其他建议? – camnuel

+0

https://stackoverflow.com/questions/35230890/how-to-reuse-mongodb-connection-through-promise – agm1984