Skip to content

Commit

Permalink
chore: use env vars in my db-init
Browse files Browse the repository at this point in the history
  • Loading branch information
kasir-barati committed Sep 11, 2024
1 parent 5de7890 commit eec280b
Show file tree
Hide file tree
Showing 7 changed files with 37 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
MONGO_INITDB_DATABASE=app
MONGO_INITDB_ROOT_USERNAME=root
MONGO_INITDB_ROOT_PASSWORD=pass
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# How to run it

1. `cp .env.example .env`
2. `docker compose up -d`
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ services:
exec docker-entrypoint.sh $$@
command: mongod --bind_ip_all --replSet rs0 --keyFile /data/replica.key
environment:
MONGO_INITDB_DATABASE: app
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: pass
MONGO_INITDB_DATABASE: ${MONGO_INITDB_DATABASE}
MONGO_INITDB_ROOT_USERNAME: ${MONGO_INITDB_ROOT_USERNAME}
MONGO_INITDB_ROOT_PASSWORD: ${MONGO_INITDB_ROOT_PASSWORD}
healthcheck:
test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')"]
interval: 5s
Expand All @@ -37,7 +37,7 @@ services:
db:
condition: service_healthy
command: >
mongosh --username root --password pass --host db:27017 --eval
mongosh --username ${MONGO_INITDB_ROOT_USERNAME} --password ${MONGO_INITDB_ROOT_PASSWORD} --host db:27017 --eval
'
rs.initiate( {
_id : "rs0",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,25 @@
// @ts-check

import mongoose from "mongoose";
import { config } from "dotenv";
import { join } from "path";

mongoose.connect("mongodb://root:pass@db:27017", {
config({
path: [join(process.cwd(), ".env")],
});

const {
MONGO_INITDB_DATABASE,
MONGO_INITDB_ROOT_USERNAME,
MONGO_INITDB_ROOT_PASSWORD,
} = process.env;
const connectionString = `mongodb://${MONGO_INITDB_ROOT_USERNAME}:${MONGO_INITDB_ROOT_PASSWORD}@db:27017`;

mongoose.connect(connectionString, {
replicaSet: "rs0",
autoIndex: true,
autoCreate: true,
dbName: "app",
dbName: MONGO_INITDB_DATABASE,
});

const catSchema = new mongoose.Schema({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.4.5",
"mongoose": "^8.6.1"
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit eec280b

Please sign in to comment.