Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
          });
        });
      });
    });
  });
like image 826
Helloworld Avatar asked May 13 '14 20:05

Helloworld


People also ask

What is MongoDB NodeJS driver?

The official MongoDB Node. js driver allows Node. js applications to connect to MongoDB and work with data. The driver features an asynchronous API which allows you to interact with MongoDB using Promises or via traditional callbacks.

How we connect MongoDB with NodeJS?

To connect a Node. js application to MongoDB, we have to use a library called Mongoose. mongoose. connect("mongodb://localhost:27017/collectionName", { useNewUrlParser: true, useUnifiedTopology: true });


2 Answers

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.

like image 114
Andras Avatar answered Oct 03 '22 11:10

Andras


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);
    });
  });
});
like image 24
Helloworld Avatar answered Oct 03 '22 11:10

Helloworld