7

In my CI I need to make sure that my code works with mongo and so I'm using the official mongo docker image and passing my desired credentials as environment variables for the mongo image.

build-on-mongo:
    runs-on: ${{ matrix.os }}
    env:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: password
      MONGO_INITDB_DATABASE: vote-stuysu-org
    services:
      mongo:
        image: mongo
        ports:
          # Maps tcp port 27017 on service container to the host
          - 27017:27017
    strategy:
      matrix:
        os: [ubuntu-20.04]
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v1
        with:
          node-version: '14.x'
      - name: Install dependencies
        run: npm install

      - name: Test
        run: npm test
        env:
          MONGO_URL: mongodb://root:password@localhost:27017/vote-stuysu-org

However, in the test step, an error gets logged saying:

(node:2158) UnhandledPromiseRejectionWarning: MongoError: Authentication failed.

I'm using mongoose alongside nodejs and so this is the code responsible for authentication:

mongoose.connect(process.env.MONGO_URL, {
    useUnifiedTopology: true,
    useNewUrlParser: true
});

I don't think that my connection uri is wrong but I'm not sure why the authentication is failing.

Abir Taheer
  • 2,502
  • 3
  • 12
  • 34
  • any solution to this? – kctang Oct 15 '20 at 07:53
  • Have you checked [this one](https://stackoverflow.com/questions/66317184/github-actions-cannot-connect-to-mongodb-service)? Even though it's not written in JS, it still has the same Github action implementation. – carkod Oct 04 '21 at 21:21

1 Answers1

0

Hey this is kinda late but maybe it will help someone. For me, I included the authSource=admin as a query param in the MongoDB connection url and it worked, here's an example:

mongodb://${MONGODB_USERNAME}:${MONGODB_PASSWORD}@localhost:${MONGODB_PORT}/${MONGODB_DB}?authMechanism=DEFAULT&authSource=admin;

I didn't have to include ${MONGODB_DB} in the connection string and make an env variable for it, that's only if you want to use a custom db name.

I learned this by using MongoDB Compass, the free native GUI app that lets you connect to MongoDB databases: https://www.mongodb.com/products/compass

Tyler2P
  • 2,324
  • 26
  • 22
  • 31