Getting started with Node.jsnpmWeb Apps With ExpressFilesystem I/OExporting and Consuming ModulesExporting and Importing Module in node.jsInstalling Node.jsMySQL integrationReadlinepackage.jsonEvent EmittersAutoreload on changesEnvironmentCallback to PromiseExecuting files or commands with Child ProcessesCluster ModuleException handlingKeep a node application constantly runningUninstalling Node.jsnvm - Node Version ManagerhttpUsing StreamsDeploying Node.js applications in productionSecuring Node.js applicationsMongoose Libraryasync.jsFile uploadSocket.io communicationMongodb integrationHandling POST request in Node.jsSimple REST based CRUD APITemplate frameworksNode.js Architecture & Inner WorkingsDebugging Node.js applicationNode server without frameworkNode.JS with ES6Interacting with ConsoleCassandra IntegrationCreating API's with Node.jsGraceful ShutdownUsing IISNode to host Node.js Web Apps in IISCLINodeJS FrameworksgruntUsing WebSocket's with Node.JSmetalsmithParsing command line argumentsClient-server communicationNode.js Design FundamentalConnect to MongodbPerformance challengesSend Web NotificationRemote Debugging in Node.JSMysql Connection PoolDatabase (MongoDB with Mongoose)Good coding styleRestful API Design: Best PracticesDeliver HTML or any other sort of fileTCP SocketsHackBluebird PromisesAsync/AwaitKoa Framework v2Unit testing frameworksECMAScript 2015 (ES6) with Node.jsRouting ajax requests with Express.JSSending a file stream to clientNodeJS with RedisUsing Browserfiy to resolve 'required' error with browsersNode.JS and MongoDB.Passport integrationDependency InjectionNodeJS Beginner GuideUse Cases of Node.jsSequelize.jsPostgreSQL integrationHow modules are loadedNode.js with OracleSynchronous vs Asynchronous programming in nodejsNode.js Error ManagementNode.js v6 New Features and ImprovementEventloopNodejs Historypassport.jsAsynchronous programmingNode.js code for STDIN and STDOUT without using any libraryMongoDB Integration for Node.js/Express.jsLodashcsv parser in node jsLoopback - REST Based connectorRunning node.js as a serviceNode.js with CORSGetting started with Nodes profilingNode.js PerformanceYarn Package ManagerOAuth 2.0Node JS LocalizationDeploying Node.js application without downtime.Node.js (express.js) with angular.js Sample codeNodeJs RoutingCreating a Node.js Library that Supports Both Promises and Error-First CallbacksMSSQL IntergrationProject StructureAvoid callback hellArduino communication with nodeJsN-APIMultithreadingWindows authentication under node.jsRequire()Route-Controller-Service structure for ExpressJSPush notifications

Mongodb integration

Other topics

Connect to MongoDB

Connect to MongoDB, print 'Connected!' and close the connection.

const MongoClient = require('mongodb').MongoClient;

var url = 'mongodb://localhost:27017/test';

MongoClient.connect(url, function(err, db) { // MongoClient method 'connect'
    if (err) throw new Error(err);
    console.log("Connected!");
    db.close(); // Don't forget to close the connection when you are done
});

MongoClient method Connect()

MongoClient.connect(url, options, callback)

ArgumentTypeDescription
urlstringA string specifying the server ip/hostname, port and database
optionsobject(optional) Optional settings (default: null)
callbackFunctionFunction to be called when the connection attempt is done

The callback function takes two arguments

  • err : Error - If an error occurs the err argument will be defined
  • db : object - The MongoDB instance

Insert a document

Insert a document called 'myFirstDocument' and set 2 properties, greetings and farewell

const MongoClient = require('mongodb').MongoClient;

const url = 'mongodb://localhost:27017/test';

MongoClient.connect(url, function (err, db) {
  if (err) throw new Error(err);
  db.collection('myCollection').insertOne({ // Insert method 'insertOne'
    "myFirstDocument": {
      "greetings": "Hellu",
      "farewell": "Bye"
    }
  }, function (err, result) {
    if (err) throw new Error(err);
    console.log("Inserted a document into the myCollection collection!");
    db.close(); // Don't forget to close the connection when you are done
  });
});

Collection method insertOne()

db.collection(collection).insertOne(document, options, callback)

ArgumentTypeDescription
collectionstringA string specifying the collection
documentobjectThe document to be inserted into the collection
optionsobject(optional) Optional settings (default: null)
callbackFunctionFunction to be called when the insert operation is done

The callback function takes two arguments

  • err : Error - If an error occurs the err argument will be defined
  • result : object - An object containing details about the insert operation

Read a collection

Get all documents in the collection 'myCollection' and print them to the console.

const MongoClient = require('mongodb').MongoClient;

const url = 'mongodb://localhost:27017/test';

MongoClient.connect(url, function (err, db) {
  if (err) throw new Error(err);
  var cursor = db.collection('myCollection').find(); // Read method 'find'
  cursor.each(function (err, doc) {
    if (err) throw new Error(err);
    if (doc != null) {
      console.log(doc); // Print all documents
    } else {
      db.close(); // Don't forget to close the connection when you are done
    }
  });
});

Collection method find()

db.collection(collection).find()

ArgumentTypeDescription
collectionstringA string specifying the collection

Update a document

Find a document with the property { greetings: 'Hellu' } and change it to { greetings: 'Whut?' }

const MongoClient = require('mongodb').MongoClient;

const url = 'mongodb://localhost:27017/test';

MongoClient.connect(url, function (err, db) {
    if (err) throw new Error(err);
    db.collection('myCollection').updateOne({ // Update method 'updateOne'
        greetings: "Hellu" }, 
        { $set: { greetings: "Whut?" }},
        function (err, result) {
            if (err) throw new Error(err);
            db.close(); // Don't forget to close the connection when you are done
        });
});

Collection method updateOne()

db.collection(collection).updateOne(filter, update, options. callback)

ParameterTypeDescription
filterobjectSpecifies the selection critera
updateobjectSpecifies the modifications to apply
optionsobject(optional) Optional settings (default: null)
callbackFunctionFunction to be called when the operation is done

The callback function takes two arguments

  • err : Error - If an error occurs the err argument will be defined
  • db : object - The MongoDB instance

Delete a document

Delete a document with the property { greetings: 'Whut?' }

const MongoClient = require('mongodb').MongoClient;

const url = 'mongodb://localhost:27017/test';

MongoClient.connect(url, function (err, db) {
    if (err) throw new Error(err);
    db.collection('myCollection').deleteOne(// Delete method 'deleteOne'
        { greetings: "Whut?" },
        function (err, result) {
            if (err) throw new Error(err);
            db.close(); // Don't forget to close the connection when you are done
    });
});

Collection method deleteOne()

db.collection(collection).deleteOne(filter, options, callback)

ParameterTypeDescription
filterobjectA document specifying the selection critera
optionsobject(optional) Optional settings (default: null)
callbackFunctionFunction to be called when the operation is done

The callback function takes two arguments

  • err : Error - If an error occurs the err argument will be defined
  • db : object - The MongoDB instance

Delete multiple documents

Delete ALL documents with a 'farewell' property set to 'okay'.

const MongoClient = require('mongodb').MongoClient;

const url = 'mongodb://localhost:27017/test';

MongoClient.connect(url, function (err, db) {
    if (err) throw new Error(err);
    db.collection('myCollection').deleteMany(// MongoDB delete method 'deleteMany'
        { farewell: "okay" }, // Delete ALL documents with the property 'farewell: okay'
        function (err, result) {
            if (err) throw new Error(err);
            db.close(); // Don't forget to close the connection when you are done
    });
});

Collection method deleteMany()

db.collection(collection).deleteMany(filter, options, callback)

ParameterTypeDescription
filterdocumentA document specifying the selection critera
optionsobject(optional) Optional settings (default: null)
callbackfunctionFunction to be called when the operation is done

The callback function takes two arguments

  • err : Error - If an error occurs the err argument will be defined
  • db : object - The MongoDB instance

Simple connect

MongoDB.connect('mongodb://localhost:27017/databaseName', function(error, database) {
   if(error) return console.log(error);
   const collection = database.collection('collectionName');
   collection.insert({key: 'value'}, function(error, result) {
      console.log(error, result);
   });
});

Simple connect, using promises

const MongoDB = require('mongodb');

MongoDB.connect('mongodb://localhost:27017/databaseName')
    .then(function(database) {
        const collection = database.collection('collectionName');
        return collection.insert({key: 'value'});
    })    
    .then(function(result) {
        console.log(result);
    });
    ```

Syntax:

  • db.collection.insertOne(document, options(w, wtimeout, j, serializeFuntions, forceServerObjectId, bypassDocumentValidation), callback)
  • db.collection.insertMany([documents], options(w, wtimeout, j, serializeFuntions, forceServerObjectId, bypassDocumentValidation), callback)
  • db.collection.find(query)
  • db.collection.updateOne(filter, update, options(upsert, w, wtimeout, j, bypassDocumentValidation), callback)
  • db.collection.updateMany(filter, update, options(upsert, w, wtimeout, j), callback)
  • db.collection.deleteOne(filter, options(upsert, w, wtimeout, j), callback)
  • db.collection.deleteMany(filter, options(upsert, w, wtimeout, j), callback)

Parameters:

ParameterDetails
documentA javascript object representing a document
documentsAn array of documents
queryAn object defining a search query
filterAn object defining a search query
callbackFunction to be called when the operation is done
options(optional) Optional settings (default: null)
w(optional) The write concern
wtimeout(optional) The write concern timeout. (default: null)
j(optional) Specify a journal write concern (default: false)
upsert(optional) Update operation (default: false)
multi(optional) Update one/all documents (default: false)
serializeFunctions(optional) Serialize functions on any object (default: false)
forceServerObjectId(optional) Force server to assign _id values instead of driver (default: false)
bypassDocumentValidation(optional) Allow driver to bypass schema validation in MongoDB 3.2 or higher (default: false)

Contributors

Topic Id: 5002

Example Ids: 17637,17638,17639,17640,17641,17642,21714,21715

This site is not affiliated with any of the contributors.