pretty code

2018年2月14日 星期三

Init MongoDB database with javascript

MongoDB Version:3.6

Steps:
1. run mongod
2. run mongo
3. load('xxxx.js')
4. run "init()"

the content of xxxx.js

var d_admin = {
    user: 'd_admin',
    pwd: 'xxxx',
    roles: [
        {
            role: 'readWrite',
            db: 'test'
        }
    ]
}

var d_user = {
    user: 'd_user',
    pwd: 'xxxx',
    roles: [
        {
            role: 'read',
            db: 'test'
        }
    ]
}

var admin = {
    user: 'root',
    pwd: 'xxxx',
    roles: [
        {
            role: 'root',
            db: 'admin'
        }
    ]
}

function init() {
    db = connect('localhost:27017');
    db = db.getSiblingDB('admin');
    db.createUser(admin);

    db = db.getSiblingDB('test');
    db.createCollection('collection1');
    db.createCollection('collection2');
    db.createUser(d_admin);
    db.createUser(d_user);
    db.getLastError();
}

沒有留言: