Unable to make mongodb connection using adonis and mongodb

Viewed 12

I am trying to make connection to mongodb. I am using adonisJS and Mongoose. Mongodb connection string is correct and I have created todo database. But I am getting Authentication failed error.

MongoServerError: Authentication failed.
    at Connection.onMessage (/opt/projects/demo/adonis-demo/adonis-mongoose-project/node_modules/mongodb/src/cmap/connection.ts:438:20)
    at MessageStream.<anonymous> (/opt/projects/demo/adonis-demo/adonis-mongoose-project/node_modules/mongodb/src/cmap/connection.ts:256:56)
    at MessageStream.emit (events.js:376:20)
    at processIncomingData (/opt/projects/demo/adonis-demo/adonis-mongoose-project/node_modules/mongodb/src/cmap/message_stream.ts:193:14)
    at MessageStream._write (/opt/projects/demo/adonis-demo/adonis-mongoose-project/node_modules/mongodb/src/cmap/message_stream.ts:70:5)
    at writeOrBuffer (internal/streams/writable.js:358:12)
    at MessageStream.Writable.write (internal/streams/writable.js:303:10)
    at Socket.ondata (internal/streams/readable.js:745:22)
    at Socket.emit (events.js:376:20)
    at addChunk (internal/streams/readable.js:309:12) {
  ok: 0,
  code: 18,
  codeName: 'AuthenticationFailed',
  [Symbol(errorLabels)]: Set(1) { 'HandshakeError' }
}

My Controller as below,

'use strict'

import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import mongoose, { Schema } from 'mongoose'

const MONGOURI ='mongodb://root:1234@localhost:27017/todo';

export default class TasksController {
constructor() {
    (async ()=>{
      await this.connection();
    })();
  }

  public async connection() {
    try {
      await mongoose.connect(MONGOURI);
      mongoose.connection.once('open', (abc) => {
        console.log('Server running on port ',abc);
      });
      mongoose.connection.on('error', error => console.error(error));
    } catch (error) {
      console.log("Catch Error: ",error);
    }    
  }

  public async index ({ }: HttpContextContract) {
      
      const Task = mongoose.model('Task', new Schema({
        name: String,
        description:String
      }))

    // Create a task with random name
    const task = new Task({
      name: Math.random().toString(36).substring(7),
      description: "THis is description of the task."
    })
    await task.save();

      const tasks = await Task.find();
      return tasks;

    // Close the connection
    //await mongoose.connection.close()

  } 
}

Has someone done this type of code? Please suggest me the edits in the above code.

1 Answers

This could be due to a custom mongoDB configuration cause the default doesn’t throw these kind of errors. You should double check your configuration file and check differences compared with the default. I would suggest try passing your connect method some options like: tlsInsecure: false, secureProtocol: ‘TLS_method’ or even tls: false.

Related