11

How do I programmatically create a database using the MongoDB Node.JS driver?

This looks promising, but I'm not sure how to connect to with the admin credentials and create a new database.

var db = new Db('test', new Server('locahost', 27017));
  // Establish connection to db
  db.open(function(err, db) {
    assert.equal(null, err);

    // Add a user to the database
    db.addUser('user3', 'name', function(err, result) {
      assert.equal(null, err);

      // Authenticate
      db.authenticate('user3', 'name', function(err, result) {
        assert.equal(true, result);

        // Logout the db
        db.logout(function(err, result) {
          assert.equal(true, result);

          // Remove the user
          db.removeUser('user3', function(err, result) {
            assert.equal(true, result);

            db.close();
          });
        });
      });
    });
  });
1
  • 1
    Are you saying you tried this and it didn't work, or did you just copy and paste it in here? I'd strongly suggest you at least try something and then post here with specific questions. Commented May 13, 2014 at 20:44

4 Answers 4

6

in mongodb databases and collections are created on first access. When the new user first connects and touches their data, their database will get created then.

Sign up to request clarification or add additional context in comments.

Comments

3

This seems to work.

var Db = require('mongodb').Db, 
Server = require('mongodb').Server;

var db = new Db('test', new Server('localhost', 27017));
db.open(function (err, db) {
  if (err) throw err;

  // Use the admin database for the operation
  var adminDb = db.admin();

  adminDb.authenticate('adminLogin', 'adminPwd', function (err, result) {
    db.addUser('userLogin', 'userPwd', function (err, result) {
      console.log(err, result);
    });
  });
});

1 Comment

Can you explain what is the difference between var db = new Db('test', new Server('localhost', 27017)); and mongoClient.connect(connString, function(err, db) ....
2

Try as below:

var adminuser = "admin";
var adminpass = "admin";
var server = "localhost";
var port   = 27017; 
var dbName = "mydatabase";
var mongodb          = require('mongodb');
var mongoClient = mongodb.MongoClient;

var connString = "mongodb://"+adminuser+":"+adminpass+"@"+server+":"+port+"/"+dbName;
    mongoClient.connect(connString, function(err, db) {
        if(!err) {
            console.log("\nMongo DB connected\n");                
        }
        else{
            console.log("Mongo DB could not be connected");
            process.exit(0);
        }
    });

Comments

0
const { MongoClient} = require("mongodb");

const uri = "mongodb://localhost:27017";

const client = new MongoClient(uri);

async function initializeDatabase() {
  try {

    await client.connect();
    console.log("Connected to the database");


    const database = client.db("mydatabase");


    module.exports = database;
  } catch (error) {
    console.error("Error initializing database:", error);
  }
}

initializeDatabase();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.