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

Javascriptnode.jsMongodbAuthenticationConnection

Javascript Problem Overview


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( 'mongolab.com', 27017, {}), {}); 

Where do I put the username and the password?

Also how do I insert something?

Thanks.

Javascript Solutions


Solution 1 - Javascript

Per the source:

After connecting:

Db.authenticate(user, password, function(err, res) {
  // callback
});

Solution 2 - Javascript

Everyone should use this source link:

http://mongodb.github.com/node-mongodb-native/contents.html

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("127.0.0.1", 27017,
 {auto_reconnect: false, poolSize: 4}), {w:0, native_parser: false});

// Establish connection to db
db.open(function(err, 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);

      db.close();
    });
  });
});

Solution 3 - Javascript

var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;	
MongoClient.connect('mongodb://'+DATABASEUSERNAME+':'+DATABASEPASSWORD+'@'+DATABASEHOST+':'DATABASEPORT+'/'+DATABASENAME,function(err, db){  
	  if(err) 
		console.log(err);
	  else
	  {
		console.log('Mongo Conn....');
		
	  }
	});
//for local server 
//in local server DBPASSWOAD and DBusername not required
MongoClient.connect('mongodb://'+DATABASEHOST+':'+DATABASEPORT+'/'+DATABASENAME,function(err, db){  
	  if(err) 
		console.log(err);
	  else
	  {
		console.log('Mongo Conn....');
		
	  }
	});

Solution 4 - Javascript

I find using a Mongo url handy. I store the URL in an environment variable and use that to configure servers whilst the development version uses a default url with no password.

The URL has the form:

export MONGODB_DATABASE_URL=mongodb://USERNAME:PASSWORD@DBHOST:DBPORT/DBNAME

Code to connect this way:

var DATABASE_URL = process.env.MONGODB_DATABASE_URL || mongodb.DEFAULT_URL;

mongo_connect(DATABASE_URL, mongodb_server_options, 
	  function(err, db) { 

	      if(db && !err) {
		  console.log("connected to mongodb" + " " + lobby_db);
	      }
	      else if(err) {
		  console.log("NOT connected to mongodb " + err + " " + lobby_db);
	      }
	  });    

Solution 5 - Javascript

My version:

var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://user:pass@dhost:port/baseName', function(err, db) {
    if (err) {
        console.error(err);
    }
    var collection = db.collection('collectionName');
    collection.find().toArray(function(err, docs) {
        console.log(docs);
    });
});

Solution 6 - Javascript

I recommend mongoskin I just created.

var mongo = require('mongoskin');
var db = mongo.db('admin:pass@localhost/mydb?auto_reconnnect');
db.collection('mycollection').find().toArray(function(err, items){
   // do something with items
});

Is mongoskin sync? Nop, it is async.

Solution 7 - Javascript

Here is new may to authenticate from "admin" and then switch to your desired DB for further operations:

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

var user = 'user';
var password = 'password';

MongoClient.connect('mongodb://'+user+':'+password+'@localhost:27017/opsdb',{native_parser:true, authSource:'admin'}, function(err,db){
	if(err){
		console.log("Auth Failed");
		return;
	}
	console.log("Connected");
	db.collection("cols").find({loc:{ $eq: null } }, function(err, docs) {
	    docs.each(function(err, doc) {
	      if(doc) {
	        console.log(doc['_id']);
	      }
	    });
	});

	db.close();

}); 

Solution 8 - Javascript

This worked for me:

Db.admin().authenticate(user, password, function() {} );

Solution 9 - Javascript

You can do it like this

var db = require('mongo-lite').connect('mongodb://localhost/test')

more details ...

Solution 10 - Javascript

if you continue to have problems with the native driver, you can also check out sleepy mongoose. It's a python REST server that you can simply access with node request to get to your Mongo instance. http://www.snailinaturtleneck.com/blog/2010/02/22/sleepy-mongoose-a-mongodb-rest-interface/

Solution 11 - Javascript

With the link provided by @mattdlockyer as reference, this worked for me:

var mongo = require('mongodb');
var server = new mongo.Server(host, port, options);
db = new mongo.Db(mydb, server, {fsync:true});
db.open(function(err, db) {
    if(!err) {
        console.log("Connected to database");
        db.authenticate(user, password, function(err, res) {
            if(!err) {
                console.log("Authenticated");
            } else {
                console.log("Error in authentication.");
                console.log(err);
            }
        });
    } else {
        console.log("Error in open().");
        console.log(err);
    };
});

exports.testMongo = function(req, res){
    db.collection( mycollection, function(err, collection) {
        collection.find().toArray(function(err, items) {
            res.send(items);
        });
    });
};

Solution 12 - Javascript

Slight typo with Chris' answer.

Db.authenticate(user, password, function({ // callback }));

should be

Db.authenticate(user, password, function(){ // callback } );

Also depending on your mongodb configuration, you may need to connect to admin and auth there first before going to a different database. This will be the case if you don't add a user to the database you're trying to access. Then you can auth via admin and then switch db and then read or write at will.

Solution 13 - Javascript

const { MongoClient } = require('mongodb');
// or as an es module:
// import { MongoClient } from 'mongodb'

// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

// Database Name
const dbName = 'myProject';

async function main() {
  // Use connect method to connect to the server
  await client.connect();
  console.log('Connected successfully to server');
  const db = client.db(dbName);
  const collection = db.collection('documents');

  // the following code examples can be pasted here...

  return 'done.';
}

main()
   //what to do next
  .then(console.log)
   //if there is an error
  .catch(console.error)
  // what to do in the end(function result won't matter here, it will execute always).
  .finally(() => client.close());

you can find more in the documentation here: https://mongodb.github.io/node-mongodb-native/4.1/

Solution 14 - Javascript

I'm using Mongoose to connect to mongodb. Install mongoose npm using following command

> npm install mongoose

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/database_name', function(err){
	if(err){
		console.log('database not connected');
	}
});
var Schema = mongoose.Schema;
var userschema = new Schema ({});
var user = mongoose.model('collection_name', userschema);

we can use the queries like this

user.find({},function(err,data){
		 if(err){
		 console.log(err);
		 }
		console.log(data);
    });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarkView Question on Stackoverflow
Solution 1 - JavascriptChris HealdView Answer on Stackoverflow
Solution 2 - JavascriptmattdlockyerView Answer on Stackoverflow
Solution 3 - JavascriptViral PatelView Answer on Stackoverflow
Solution 4 - JavascriptjustinhjView Answer on Stackoverflow
Solution 5 - Javascriptcn007bView Answer on Stackoverflow
Solution 6 - Javascriptguilin 桂林View Answer on Stackoverflow
Solution 7 - JavascriptjollyView Answer on Stackoverflow
Solution 8 - JavascriptjwchangView Answer on Stackoverflow
Solution 9 - JavascriptAlex CraftView Answer on Stackoverflow
Solution 10 - JavascriptRayView Answer on Stackoverflow
Solution 11 - JavascriptRVCView Answer on Stackoverflow
Solution 12 - JavascriptearlonrailsView Answer on Stackoverflow
Solution 13 - JavascriptSoufianeView Answer on Stackoverflow
Solution 14 - JavascriptvamsikrishnamannemView Answer on Stackoverflow