46 lines
1.1 KiB
JavaScript
46 lines
1.1 KiB
JavaScript
// This script initializes MongoDB with a replica set and creates a default database with user
|
|
db = db.getSiblingDB('admin');
|
|
|
|
// Wait for the MongoDB instance to be ready
|
|
print("Waiting for MongoDB to be ready...");
|
|
let counter = 0;
|
|
while (!db.adminCommand({ ping: 1 }).ok && counter < 30) {
|
|
sleep(1000);
|
|
counter++;
|
|
}
|
|
|
|
// Initialize replica set if not already initialized
|
|
try {
|
|
rs.status();
|
|
} catch (err) {
|
|
print("Initializing replica set...");
|
|
rs.initiate({
|
|
_id: "rs0",
|
|
members: [{ _id: 0, host: "localhost:27017" }]
|
|
});
|
|
}
|
|
|
|
// Wait for replica set to initialize
|
|
print("Waiting for replica set to initialize...");
|
|
counter = 0;
|
|
while (rs.status().ok !== 1 && counter < 30) {
|
|
sleep(1000);
|
|
counter++;
|
|
}
|
|
|
|
// Create application database and user if they don't exist
|
|
db = db.getSiblingDB('appdb');
|
|
|
|
if (!db.getUser('appuser')) {
|
|
print("Creating application user...");
|
|
db.createUser({
|
|
user: 'appuser',
|
|
pwd: 'apppassword',
|
|
roles: [
|
|
{ role: 'readWrite', db: 'appdb' }
|
|
]
|
|
});
|
|
}
|
|
|
|
print("MongoDB initialization completed successfully!");
|