Node.js - MongoDB

Updated: 2019-01-03

Native MongoDB

Source Code: https://github.com/mongodb/node-mongodb-native

Install:

$ npm install mongodb

Connect

var mongoUrl = "mongodb://[username:[email protected]]host:[port]/[db]";
var MongoClient = require("mongodb").MongoClient;

MongoClient.connect(mongoUrl, function(err, db) {
  if (err) throw err;

  var collection = db.collection("collection_name");

  // do whatever
});

Query

collection.find({ key: value }).toArray(function(err, docs) {
  if (err) throw err;

  docs.forEach(function(doc) {
    // do whatever
  });
});

Insert

collection.insert(entry, function(err, docs) {});

Mongoose

Source Code: https://github.com/Automattic/mongoose

Install:

$ npm install mongoose