Access MongoDB in Node.jsLearn how to access document-based database MongoDB using Node.js in this section.In order to access MongoDB database, we need to install MongoDB drivers. To install native drivers using NPM, open command prompt and write the following command to install MongoDB driver in your application.npm install mongodb -saveThis will include mongodb folder inside nodemodules folder. Now, start the MongoDB server using the following command.
(Assuming that your MongoDB database is at C:MyNodeJSConsoleAppMyMongoDB folder.)mongod -dbpath C:MyNodeJSConsoleAppMyMongoDBConnecting MongoDBThe following example demonstrates connecting to the local MongoDB database. In the above example, we have imported mongodb module (native drivers) and got the reference of MongoClient object. Then we used MongoClient.connect method to get the reference of specified MongoDB database.The specified URL 'mongodb://localhost:27017/MyDb' points to your local MongoDB database created in MyMongoDB folder.The connect method returns the database reference if the specified database is already exists, otherwise it creates a new database.Now you can write insert/update or query the MongoDB database in the callback function of the connect method using db parameter. Insert DocumentsThe following example demonstrates inserting documents into MongoDB database. In the above example, db.collection method creates or gets the reference of the specified collection. Collection is similar to table in relational database. We created a collection called Persons in the above example and insert three documents (rows) in it.
Node.js – Delete Collection in MongoDB. In this Node.js Tutorial, we shall learn to Delete Collection in MongoDB from Node.js Application, using db.collection.remove method, with an example. Following is a step by step guide with an example to delete a collection in MongoDB from Node.js Application.
After that, we display the count of total documents stored in the collection.Running the above example displays the following result. node app.jsTotal Rows: 3Update/Delete DocumentsThe following example demonstrates updating or deleting an existing documents(records).