简体   繁体   中英

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();
          });
        });
      });
    });
  });

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.

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);
    });
  });
});

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);
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM