Both of these are use to handle operations. When we talk about  Asynchronous vs Synchronous we basically talk about IO operations so we can say  Asynchronous vs Synchronous IO.

If we compare mongodb and node.js on the basis of  Asynchronous vs Synchronous then
Mongodb comes under the categorie of  Synchronous
Node.js comes under the categorie of Asynchronous

Synchronous Example :

Note : In this example we use “findOne()” which is used to return one document that satisfies the specified query criteria. If multiple documents satisfy the query, this method returns the first document according to the natural order.

Code :
//Find one document 
var doc = db.<collection_name>.findOne();

//Print result
printjson(doc);

Asynchronous Example :

Code :
//Create a client 
var MongoClient  = require('mongodb').MongoClient;

//Connect to server. By default Mongodb connect to 27017 port
MongoClient.connect('mongodb://localhost:27017/<database_name>', function(err, db) {
        if(err) throw err;
        // Find one document 
        db.collection('<collection_name').findOne({}, function(err, doc) {
            if(err) throw err;
                // Print result 
                console.dir(doc);

               //Close the Database
               db.close();
});

            // Declare result
            console.dir("findOne find!"); 
});

In this we also findOne like in above example but in this we are using callback function [function(err, db)]. In this error takes first parameter and return value as second parameter.

In this code, code first goes to (“// Find one document”) part then callback function first active err part if it’s true i.e if no error then it moves to (“// Declare result”) part first. It prints  ” findOne find! ” then goes back to (“// Find one document”) part for further execution.

Advertisements