Replace Mongoose with the native Node.js driver in MongoDB

Posted By : Rahul Sarkar | 29-Jan-2019

MongoDB is a popular NoSQL database. It is a document database that stores data in a flexible document, similar to JSON.

MongoDB is a distributed database, so its high availability, horizontal scalability, and geographical distribution are integrated and easy to use.

In this article, I will explain how to access MongoDB via the Mongo Node.js driver 2.4. The Node.js driver provides callback-based and commitment-based operations. A complete API reference available on the MongoDB site.

Accessing MongoDB with Mongoose will impose strict solutions and performance overloads in our development work.

The performance or flexibility provided by MongoDB has been compromised. Instead, we can try the Mongo Node.js driver, which provides all the performance benefits of Mongo.

Let's create a project with npm init and install the MongoDB driver.

	
	npm install [email protected] --save 
	
	

Interact and connect to MongoD's MongoDao JS file to perform database operations, perform error handling, and then perform callback operations.

The app.js file is the client of the dao file, which will send/retrieve data, invoke database operations and connect all online operations.

The application file first creates a MongoDao object using the URL and then connects asynchronously. After a successful connection, it will connect to the name of the requested database.

	
	function MongoDao(mongoUri, dbname) {
		var _this = this;
		var options = {
			useNewUrlParser: true
		};
		_this.mongoClient = new MongoClient(mongoUri, options);
		return new Promise(function(resolve, reject) {
			_this.mongoClient.connect(function(err, client) {
				assert.equal(err, null);
				console.log("mongo client successfully connected \n");
				_this.dbConnection = _this.mongoClient.db(dbname);
				resolve(_this);
			});
		});
	}

	

This asynchronous operation is contained in a promise that is executed by waiting and then waits for this commitment to be fulfilled, as shown below.

	
	async function main() {
		mongoDao = await new MongoDao(url, dbName);
		insertFn();
	}
main();

	

The above code also calls an insert function that passes the name and document of the collection to mongoDao.

	
	const insertFn = function() {
		mongoDao.insertDocument(collectionName, doc, updateFn);
	}

	

The insert function in MongoDao will insert the document using the insertOne Mongo Driver method, then retrieve the same document through the callback and print it out.

	
	MongoDao.prototype.insertDocument = function(collectionName, doc, callback) {
		var _this = this;
		this.dbConnection.collection(collectionName).insertOne(doc, function(err, result) {
			assert.equal(null, err);
			console.log("Doc inserted successfully");
			_this.printDocument(collectionName, doc, callback);
		});
	}

	

The printDocument method is a Dao method that retrieves documents and filters based on approved JSON documents. It will print the record and call the callback, which is an update function (mongoDao.insertDocument(collectionName, doc, updateFn);).

	
	MongoDao.prototype.printDocument = function(collectionName, doc, callback) {
		this.dbConnection.collection(collectionName).find({}).filter(doc)
			.toArray(function(err, docs) {
				console.log(docs[0]);
				console.log("\n");
				callback();
			});
	}

	

The insert function performs the insert and then calls the provided callback. I have added an update function to update the inserted document itself.

	
	const updateFn = function() {
		var updateDoc = {
			"$set": {
				"mobile": 9123456789
			}
		};
		mongoDao.updateDocument(collectionName, doc, updateDoc, deleteFn);
	}

	

In MongoDao, this will call the updateOne API method to do this and validate the error, then print the number of update records.

	
	MongoDao.prototype.updateDocument = function(collectionName, doc, updateDocument, callback) {
		var _this = this;
		this.dbConnection.collection(collectionName).updateMany(doc, updateDocument,
			function(err, result) {
				assert.equal(null, err);
				_this.printDocument(collectionName, doc, callback);
				callback();
			});
	}

	

After the document is successfully updated, the delete function shown above (mongoDao.updateDocument(collectionName, doc, updateDoc, deleteFn);) is called. In the delete function, a document with a key value is used to locate the document passed as a parameter, so the method of the deleteOne API will be used to delete it.

	
	MongoDao.prototype.deleteDocument = function(collectionName, doc, callback) {
		this.dbConnection.collection(collectionName).deleteOne(doc, function(err, result) {
			assert.equal(null, err);
			console.log("Document deleted successfully");
			callback();
		});
	}

	

mongodao.js: All operations of the database, error handling and callback function calls.

app.js - The client that passes the data and retrieves the data from mongodao.js.

 

Thanks,

About Author

Author Image
Rahul Sarkar

Rahul is an intellectual web app developer, he has good knowledge of C, Java, Java Script, Jquery. Apart from this he likes to travel and explore new places.

Request for Proposal

Name is required

Comment is required

Sending message..