Created
January 28, 2015 23:11
-
-
Save chrisckchang/e8d0aada37d2dfd89b7d to your computer and use it in GitHub Desktop.
dynamically create databases. help from http://jxcore.com/mongodb-2-6-with-jxcorenode-js-creating-admin-regular-users/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var MongoClient = require('mongodb').MongoClient, | |
| Server = require('mongodb').Server, | |
| Db = require('mongodb').Db, | |
| ReplSetServers = require('mongodb').ReplSetServers; | |
| var url = 'MONGODB_URI'; | |
| // You can connect to any database here. Likely whichever connection you want to be persistent | |
| MongoClient.connect(url, function(err, uriDb) { | |
| if(err) console.log(err); | |
| var replSet = new ReplSetServers([ | |
| new Server('HOST1', PORT1), | |
| new Server('HOST2', PORT2) | |
| ]); | |
| // Construct new DB "foo" | |
| var fooDb = new Db('foo', replSet, {safe: true}); | |
| // Establish connection to new DB "foo" | |
| fooDb.open(function(err, db) { | |
| // Get to the admin database | |
| var adminDb = db.admin(); | |
| // Authenticate by way of the admin database | |
| adminDb.authenticate('adminUser','adminPass', function(err, result) { | |
| // Add new user to the new DB "foo" | |
| db.addUser('user1', 'pass1', {"roles": ["readWrite"]},function(err, result) { | |
| // Authenticate on "foo" database | |
| db.authenticate('user1', 'pass1', function(err, result) { | |
| // Do queries to test connection | |
| var coll = db.collection('coll'); | |
| coll.insert({"doc": "test"}, function(err, result){ | |
| if (err) throw err; | |
| coll.find({}).toArray(function (err, docs) { | |
| if(err) throw err; | |
| docs.forEach(function (doc) { | |
| console.log(doc); | |
| }); | |
| }); | |
| }); | |
| }); | |
| }); | |
| }); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment