Home > Back-end >  Winston MongoDB - Authentication error when passing the database
Winston MongoDB - Authentication error when passing the database

Time:04-06

I'm opening this issue because I'm not sure if this only happens to me.

I'm having trouble connecting to the database when in the mongo url I pass the database. I'm using a structure similar to this:

const logger = winston.createLogger({
  levels: customLevels,
  format: winston.format.combine(
    winston.format.errors({ stack: true }),
    winston.format.json(),
    winston.format.timestamp(),
  ),
  transports: [
    new winston.transports.MongoDB({
      db: `mongodb://user:pass@host:port/database`,
      tryReconnect: true,
      collection: 'logs',
      options: { useNewUrlParser: true, useUnifiedTopology: true }
    }),
  ],
});

But when trying to connect, I get the following error:

winston-mongodb: will try reconnecting in 10 seconds
winston-mongodb: error initialising logger MongoError: Authentication failed.

When I remove the database from the connection string from mongodb it connects and creates a database called "test" on mongo. The username and password are correct, as I entered the same data to create the database I am trying to connect.

Anyone else going through something similar?

CodePudding user response:

Most probably you will need to add the authentication database in your uri as follow:

 db: `mongodb://user:pass@host:port/database?authSource=admin`

Otherways mongo will search the user in your provided "database" ...

  • Related