I'm trying to connect to a mongodb container using mongoose. This is my docker-compose:
version: "3"
networks:
mongonet:
services:
mongodatabase:
image: mongo
container_name: mongodatabase
ports:
- 27017:27017
environment:
- MONGO_INITDB_DATABASE=admin
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=root
networks:
- mongonet
mongojs:
depends_on:
mongodatabase:
condition: service_started
container_name: mongojs
build: .
ports:
- 8080:8080
environment:
- MONGO_URI=mongodb://mongodatabase:27017/test
networks:
- mongonet
Containers start and work ok, but problems appear when using mongoose:
const mongoose = requrie('mongoose')
const {MONGO_URI} = require('./../config/env')
exports.__mongo_ini = async function () {
const connectOptions = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
try {
await mongoose.connect(MONGO_URI, connectOptions)
console.info(`===> Connected to database ${MONGO_URI}`)
}
catch(err) {
console.warn(`===> Couldn't connect: ${err}`)
}
}
When using the env URI mongodb://mongodatabase:27017/test It says connected. But then If I try to find a model:
await models.Star.find().catch(r => r)
I get the error:
MongoServerError: command find requires authentication
at Connection.onMessage (/usr/src/app/node_modules/mongodb/lib/cmap/connection.js:203:30)
at MessageStream.<anonymous> (/usr/src/app/node_modules/mongodb/lib/cmap/connection.js:63:60)
....
ok: 0,
code: 13,
codeName: 'Unauthorized',
[Symbol(errorLabels)]: Set(0) {}
}
My model:
const starSchema = new mongoose.Schema({
starName: {
type: String,
unique: true,
required: true
},
image: {
type: String
},
designation: {
type: String
},
constelation: {
type: String
},
named: {
type: Date
},
timeStamp: {
type: Date,
default: Date.now()
}
})
const Star = mongoose.model('Star',starSchema)
module.exports = Star
Tried to add a mongo entrypoint volume in my docker compose:
volumes:
- ./mongo-entrypoint/mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
Mongo-init.js:
db.getSiblingDB('admin').createUser({
user: 'testuser',
pwd: 'testpass',
roles: [
{
role: 'readWrite',
db: 'test'
}
]
})
db.getSiblingDB('test').createCollection('collection_test');
So I try to connect changing the mongo uri to use user and password:
MONGO_URI=mongodb://testuser:testpass@mongodatabase:27017/test
But It says authentication failed when trying to connect to the mongo uri and the mongo entrypoint doesn't seem to run:
Couldn't connect: MongoServerError: Authentication failed.
I've tried so many things and none of them work. All help is appreciated.