How do I connect to mongodb with node.js (and authenticate)?


How do I connect to mongodb with node.js?

I have the node-mongodb-native driver.

There's apparently 0 documentation.

Is it something like this?

var mongo = require('mongodb/lib/mongodb'); 
var Db= new mongo.Db( dbname, new mongo.Server( '', 27017, {}), {}); 

Where do I put the username and the password?

Also how do I insert something?


12/2/2016 6:53:41 PM

Accepted Answer

Per the source:

After connecting:

Db.authenticate(user, password, function(err, res) {
  // callback
3/17/2013 12:51:09 PM

Everyone should use this source link:

Answer to the question:

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('integration_tests', new Server("", 27017,
 {auto_reconnect: false, poolSize: 4}), {w:0, native_parser: false});

// Establish connection to db, db) {
  assert.equal(null, err);

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

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow