0

I'm trying to build an API-REST on Node.js. I did another one before, but now I'm unable to connect to MongoDB database. This database has an auth process, but somehow, credentials aren't working as expected. I can connect locally to the database with them, but not when trying a remote connection.

I read a while about this, and it seems that, due to some updates, the connection string I'm trying to use is not working at all. Here's some code:

config.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'
}

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}`)
})
})

I know that, as always, this might be asked before, and I guess it must be the simplest thing of the world, but I'm really stuck with this s***!

Thanks in advance, guys!

EDIT: Error log

(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.
camnuel
  • 22
  • 6

1 Answers1

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

try put that option.

ZeroCho
  • 1,358
  • 10
  • 23