问题
I have a number of collections with schema validation rules that I would like to use to populate a database on the startup of a docker container using the docker-compose up --build command.
Since there are so many collections, I have separated the collections into different js files for hopefully clean directory structure and code organization and readability. Each js file exports a variable of the form
export const CollectionDeps = ["NameOfCollection", obj];
where the object is the json schema validator. E.g.,
obj = {
validator: {
$jsonSchema: {
bsonType: "object",
required: [...], // required fields
properties: {
Field1: { ... },
Field2: { ... },
Field3: { ... }
}
}
}
}
I am running on Ubuntu 18.04 and using the official mongo image from DockerHub (https://hub.docker.com/_/mongo). I have tried to follow the method that someone proposed in this question (https://stackoverflow.com/a/54064268/3716628) but it hasn't accomplished what I want.
Directory structure
home
| -- user
| -- ssl-data
| -- server.pem
| -- scripts
| -- collections
| -- Collection1
| - collection1a.js
| - collection1b.js
| -- Collection2
| - collection2a.js
mongo-init.js
docker-compose.yml
version: '3.7'
services:
mongodb:
image: mongo
container_name: mongodb
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: example
MONGO_INITDB_DATABASE: my_test_db
ports:
- 27017:27017
volumes:
- ./ssl-data/server.pem:/etc/ssl/server.pem
- ./persistent-storage-mongo:/data/db
- ./scripts/collections:/docker-entrypoint-initdb.d/collections
- ./scripts/mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro
command:
- --sslMode=requireSSL
- --sslPEMKeyFile=/etc/ssl/server.pem
- --sslPEMKeyPassword=somepassword
- --sslAllowInvalidCertificates
- --sslAllowInvalidHostnames
collections/CollectionX/collectionXn.js
export const CollectionXn = ["CollectionXn", obj] // see above for what obj is
mongo-init.js
db.auth('root', 'example');
db = db.getSiblingDB('my_test_db')
// Collection1 schemas
import Collection1a from 'collections/Collection1/collection1a.js'
import Collection1b from 'collections/Collection1/collection1b.js'
db.createCollection(Collection1a[0], Collection1a[1]);
db.createCollection(Collection1b[0], Collection1b[1]);
// Collection2 schemas
import Collection2a from 'collections/Collection2/collection2a.js'
db.createCollection(Collection2a[0], Collection2a[1]);
The container starts up after I run docker-compose up --build -d mongodb and I can connect to it and access the mongodb using ssl as I have configured, but the database (my_test_db) and collections have not been created.
Does anyone have any suggestions for where I'm going wrong?
来源:https://stackoverflow.com/questions/57209269/i-want-to-create-a-mongodb-database-and-populate-it-with-a-number-of-collections