MongoDB Docker init script

Viewed 10952

I am attempting to seed my MongoDB in Docker. my docker-compose.yml file is pretty straight forward, here is my volume though:

...
volumes:
      - ./mongo/init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js:ro
      - ./mongo/mongod.conf:/etc/mongod.conf:ro
      - ./mongo/mongo-volume:/data/db
...

I have init-mongo.js mapped as a volume, here is its contents:

db.createUser({
  user: 'root',
  pwd: 'toor',
  roles: [
    {
      role: 'readWrite',
      db: 'testDB',
    },
  ],
});
db.createCollection('users', { capped: false });
db.createCollection('test', { capped: false });

db.test.insert([
  { "item": 1 },
  { "item": 2 },
  { "item": 3 },
  { "item": 4 },
  { "item": 5 }
]);

The user root and the database testDB as well as the collections users and test are all created with no problem.

The issue is that db.test.insert([]) seems to be missed all together, and NO documents are inserted into the test collection.

Any Ideas why that is? I would absolutely love to get this working and would really appreciate any assistance with this.

Thanks, -Kevin

2 Answers

Change your init-mongo.js file to this to select the new database first, then create collections and finally seed data into them:

db.createUser({
    user: 'root',
    pwd: 'toor',
    roles: [
        {
            role: 'readWrite',
            db: 'testDB',
        },
    ],
});

db = new Mongo().getDB("testDB");

db.createCollection('users', { capped: false });
db.createCollection('test', { capped: false });

db.test.insert([
    { "item": 1 },
    { "item": 2 },
    { "item": 3 },
    { "item": 4 },
    { "item": 5 }
]);

Then login to mongo shell (use mongo -u [admin_username] -p) and check the data in the testDB collection:

use testDB;
db.getCollection('test').find()

That will show:

{ "_id" : ObjectId("5f947906cc845282e5711728"), "item" : 1 }
{ "_id" : ObjectId("5f947906cc845282e5711729"), "item" : 2 }
{ "_id" : ObjectId("5f947906cc845282e571172a"), "item" : 3 }
{ "_id" : ObjectId("5f947906cc845282e571172b"), "item" : 4 }
{ "_id" : ObjectId("5f947906cc845282e571172c"), "item" : 5 }

I think you're connected to the admin db right? Users are generally created on the admin db.

Try reinitialising your db with "testDB" db before you run the insert.

Related