MongoDB Node.js Driver and MongoClient All In One
The next generation Node.js
driver
for MongoDB
$ npm i mongodb
# OR
$ npm i -S mongodb
# OR
$ npm install mongodb --save
https://mongodb.github.io/node-mongodb-native/index.html
https://www.mongodb.com/docs/drivers/node/current/
https://learn.mongodb.com/learning-paths/using-mongodb-with-nodejs
https://mongodb.github.io/node-mongodb-native/Next/
The URL
connection format
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
// new MongoClient
https://mongodb.github.io/node-mongodb-native/api-generated/mongoclient.html
demos
var MongoClient = require('mongodb').MongoClient;
// MongoClient.connect
MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, db) {
test.equal(null, err);
test.ok(db != null);
db.collection("replicaset_mongo_client_collection").update({a:1}, {b:1}, {upsert:true}, function(err, result) {
test.equal(null, err);
test.equal(1, result);
db.close();
test.done();
});
});
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,
Grid = require('mongodb').Grid,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON,
assert = require('assert');
// Set up the connection to the local db ✅
var mongoclient = new MongoClient(new Server("localhost", 27017), {native_parser: true});
// Open the connection to the server
mongoclient.open(function(err, mongoclient) {
// Get the first db and do an update document on it
var db = mongoclient.db("integration_tests");
db.collection('mongoclient_test').update({a:1}, {b:1}, {upsert:true}, function(err, result) {
assert.equal(null, err);
assert.equal(1, result);
// Get another db and do an update document on it
var db2 = mongoclient.db("integration_tests2");
db2.collection('mongoclient_test').update({a:1}, {b:1}, {upsert:true}, function(err, result) {
assert.equal(null, err);
assert.equal(1, result);
// Close the connection
mongoclient.close();
});
});
});