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

Where do I put the username and the password?

Also how do I insert something?

Thanks.

This question is related to javascript node.js mongodb authentication connection

The answer is


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

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

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/


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....');

      }
    });

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.


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.


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

You can do it like this

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

more details ...


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

}); 

This worked for me:

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

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

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to mongodb

Server Discovery And Monitoring engine is deprecated Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Failed to start mongod.service: Unit mongod.service not found db.collection is not a function when using MongoClient v3.0 MongoError: connect ECONNREFUSED 127.0.0.1:27017 MongoDB: How To Delete All Records Of A Collection in MongoDB Shell? How to resolve Nodejs: Error: ENOENT: no such file or directory How to create a DB for MongoDB container on start up?

Examples related to authentication

Set cookies for cross origin requests How Spring Security Filter Chain works What are the main differences between JWT and OAuth authentication? http post - how to send Authorization header? ASP.NET Core Web API Authentication Token based authentication in Web API without any user interface Custom Authentication in ASP.Net-Core Basic Authentication Using JavaScript Adding ASP.NET MVC5 Identity Authentication to an existing project LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

Examples related to connection

Apache Server (xampp) doesn't run on Windows 10 (Port 80) "Proxy server connection failed" in google chrome Failed to connect to mysql at 127.0.0.1:3306 with user root access denied for user 'root'@'localhost'(using password:YES) "The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate Login to Microsoft SQL Server Error: 18456 How do I start Mongo DB from Windows? java.rmi.ConnectException: Connection refused to host: 127.0.1.1; mySQL Error 1040: Too Many Connection org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused in android What is the functionality of setSoTimeout and how it works?