Many of today’s web applications use node.js in conjunction with MongoDB to store and access data on the backend server. Not only does node.js excel in ease of access to non-relational databases like MongoDB, but brings scalability and speed to the server side of your app. Fortunately, it’s fairly simple and easy, especially with the delicious tutorial we’ve prepared just for you. With the growing popularity of MEAN (MongoDB, Express, Angular and Node) and MERN (MongoDB, Express, React and Node) stacks, proficiency in CRUD operations on NoSQL databases like MongoDB is something every app developer should have. How can a tutorial be delicious? Is using Node.js with MongoDB really simpler than ordering dinner? Keep reading to find out! Before we start cooking, let’s get to know our ingredients. Node.js . Node.js is a JavaScript runtime environment for the back-end of your application. Based on Google’s V8 JavaScript engine, Node.js includes numerous components and features necessary for web app implementation . Since it continues working on other tasks in the queue instead of waiting for the client to respond, it can perform many more operations in parallel – and thus faster. One of the main advantages of Node.js is its scalability thanks to its event-driven asynchronous engine In addition, Node.js supports the quick installation of third party packages and modules using the npm tool, which we will also use in this tutorial to install MongoDB. MongoDB . MongoDB is an open source non-relational database that stores the data in the form of collections and documents. Designed with agility and scalability in mind, MongoDB brings together the rich features of relational databases and speed of key-value stores Instead of storing data in rows and columns (as relational databases do), . Storing all related information together makes querying faster, and since MongoDB was also designed to be used asynchronously, it makes for an ideal repository for the data of Node.js applications. MongoDB stores the JSON documents in the form of collections with dynamic schemas In this tutorial, we’ll be installing MongoDB on your local machine, but for production purposes, you might want to use the MongoDB Atlas cloud database service. Environment Setup If you have yet to do so, on your machine using the file that matches your OS and processor. Once installed, run MongoDB from the command prompt of your operating system. If you use the default settings, the port on which MongoDB will listen will be 27017. download and install MongoDB Now that we have our ingredients ready, it’s time to get cooking and introduce them to one another. 1. Installing MongoDB npm Regardless of whether you have a Node.js project you’re looking to connect to a MongoDB database or you are creating a new project, you’ll need to install the MongoDB package using the Node.js Package Manager (npm). To do that, open a terminal window in your IDE of choice, and type: npm -g mongodb install This will install mongodb as a global library, so all your Node.js projects will have access to it and be able to use it. 2. Connecting to MongoDB With your kitchen (the backend) and ingredients in place, . (or any other kind of data) you’ll have in your MongoDB database. it’s time to mix those flavors Create a file in your project folder named server.js. As the name implies, this will be your server, and it will be bringing out the dishes To allow Node.js access to MongoDB as a client, you’ll need to enter the requirement in your server.js file. {MongoClient} = ( ); const require 'mongodb' To connect Node.js to the actual MongoDB database server running locally on your machine, we’ll need to specify its URL. If you didn’t make any changes in the setup process, the URL should be: url = ; const 'mongodb://localhost:27017/' CRUD Operations on MongoDB with Node.js . CRUD stands for Create, Read, Update and Delete – the basic functions you will be applying on your database. With the above lines in our server.js file, we now have access to all the CRUD functions of mongoClient So let’s start with the first: Creation. 1. Creating a MangoDB Database & Adding Documents to Collections In our mouth-watering Dinner project, we’ll be creating a database of dishes we could order. T . o start, we’ll be adding a document (a dish) into a collection named dishes in a database that we’ll (fairly unoriginally) name dishesdb Now comes the neat part about cooking with MongoDB and Node.js – . If they do not exist when we call them, they will be created when we insert a document into a collection. you don’t have to declare the names of the database and collection in advance To insert delicious dishes (documents) into our menu (collection), we can use one of two methods. , and . To add a single dish, we’ll use insertOne() to add a number of dishes at once we’ll be using insertMany() . The variable dbo is used to refer to our database (dishesdb), and in it we’re creating a collection named dishes using the method. The code below, once executed, will attempt to add a single dish, “Greens Fava Salad”, to the collection dishes in the database dishesdb collection() Since we won’t be using a frontend for the purpose of this tutorial, we’ll be tracking what happens on the server through terminal output. To view the results of script execution, we’ll use and specify a success message to display – 1 document inserted into collection dishes. console.log() Here’s a function to insert one single dish into our database, : dishesdb { client = MongoClient.connect(url, { : }); client.db(dbName).collection(collectionName).insertOne(newdish); .log( ); client.close(); } async ( ) function createOne dbName, collectionName, newdish const await useNewUrlParser true await console "1 document inserted into collection dishes" Now all we need to do is define a new dish and then call the function: newdish = { : , : , : , : }; createOne( , , newdish); let innerId 1 title 'Greens Fava Salad' description 'Tossed greens with citrus dressing.' price '$10' await 'dishesdb' 'dishes' Note that it’s important to . Leaving connections open can be a security vulnerability as well as cause errors and malfunctions. close the database connection at the completion of every interaction using client.close() In addition, if you want to simplify your code and improve performance you can . use this method to share a single database connection across your entire codebase To test it out add the code above to your server.js file and run node server.js in a terminal. If all goes well, you should receive the message – 1 document inserted into collection dishes. Inserting multiple items into your collection is very similar. You simply need to use instead of . insertMany() insertOne() Here’s a function to insert many dishes into our database, : dishesdb { client = MongoClient.connect(url, { : }); res = client.db(dbName).collection(collectionName).insertMany(mydishes); .log( , res.insertedCount); client.close(); } async ( ) function createMany dbName, collectionName, mydishes const await useNewUrlParser true const await console "Number of dishes added:" Now all we need to do is define a few dishes and then call the function: mydishes = [ { : , : , : , : }, { : , : , : , : }, { : , : , : , : }, { : , : , : , : }, { : , : , : , : } ]; createMany( , , mydishes); let innerId 2 title 'Seasonal Pumpkin Soup' description 'Hot and filling Thai Pumpkin Soup.' price '$13' innerId 3 title 'Fresh Vegetables' description 'Freshly cut vegetables with olive oil and zest.' price '$10' innerId 4 title 'New York Cheesecake' description 'Delicious Cheesecake with an accompaniment of seasonal fruits.' price '$20' innerId 5 title 'Chocolate Donut' description 'Our chef\' s recipe for a chocolate donut.' price '$15' innerId 6 title 'Watermelon Cocktail' description 'A light alcoholic cocktail to cleanse your pallet.' price '$17' await 'dishesdb' 'dishes' As you can see, in addition to the title and description of each dish, we also added our own unique identifiers for the dishes / documents (innerId) to prevent confusion between the identification scheme of our Dinner menu and the MongoDB index for documents. Now that we have some documents in a collection stored in the database, we can read them. 2. Reading from a MongoDB Database To read from the DB we can use and . To get all the content of a collection, we can use find() without any qualifying queries. find() findOne() Here’s a function using to locate all of the documents of collection in database . find() collectionName dbName { client = MongoClient.connect(url, { : }); result = client.db(dbName).collection(collectionName).find({}).toArray(); .log(result); client.close(); } async ( ) function locateAll dbName, collectionName const await useNewUrlParser true const await console Running this function for database dishesdb and collection dishes looks like this: locateAll( , ); await 'dishesdb' 'dishes' The result will be all 6 dishes that are currently listed in collection ‘dishes’. We can make the search more specific by adding a query to the function. find() For example, here is a function that accepts a specific query in addition to the and . dbName collectionName { client = MongoClient.connect(url, { : }); result = client.db(dbName).collection(collectionName).find(myQuery).toArray(); .log(result); client.close(); } async ( ) function locateByQuery dbName, collectionName, myQuery const await useNewUrlParser true const await console Here is how we define a query to locate all the dishes priced at $10 and then call the function. myquery = { : }; locateByQuery( , , myquery); let price '$10' await 'dishesdb' 'dishes' < > br myquery = { : }; locateByQuery( , , myquery); let price '$10' await 'dishesdb' 'dishes' If we’re looking to find only one specific document we can use . It works pretty much like except it will always return a single object – the first document to match the query. So if we change the above code to instead of , we’ll only get the first item on our menu to cost $10. findOne() find() findOne() find() Here’s the function that does exactly that: locateOneByQuery() { client = MongoClient.connect(url, { : }); result = client.db(dbName).collection(collectionName).findOne(myQuery); .log(result); client.close(); } async ( ) function locateOneByQuery dbName, collectionName, myQuery const await useNewUrlParser true const await console 3. Updating Documents in a MongoDB Database The next operation in CRUD is Update and as the name implies, it allows us to update documents in our MangoDB database collections. Much like with creating and reading, . To update one document we can use and to change values in a number of documents at once. updates to documents can be done in singles or in bulk updateOne() updateMany() , query. will update the first document to match it in our collection. With updateMany() you can alter the values of multiple documents that match a updateOne() Here’s a function for updating one document that expects the dbName and collectionName in addition to the query and the new values: { client = MongoClient.connect(url, { : }); res = client.db(dbName).collection(collectionName).updateOne(myQuery, newValue); .log( , res.result.nModified); client.close(); } async ( ) function renewOneByQuery dbName, collectionName, myQuery, newValue const await useNewUrlParser true const await console "number of documents updated:" For example, . From ‘Seasonal Pumpkin Soup’, we’ll change the name to ‘Autumn Pumpkin Soup’ and . let’s make our soup extra-attractive by updating the name and description include some details about the soup’s unique properties in the description The code to do that would look like this: newQuery = { : }; newValue = { : { : , : }}; renewOneByQuery( , , newQuery, newValue); let title 'Seasonal Pumpkin Soup' let $set title 'Autumn Pumpkin Soup' description 'Hot and filling Bengali Pumpkin Soup.' await 'dishesdb' 'dishes' With such appetizing names and descriptions, our dishes seem underpriced, wouldn’t you agree? So let’s raise some prices. In order to change the price of all dishes costing ‘$10’ to ‘$20’, let’s create a function that updates many documents at once based on our given query. The function code would look like this: { client = MongoClient.connect(url, { : }); res = client.db(dbName).collection(collectionName).updateMany(myQuery, newValue); .log( , res.result.nModified); client.close(); } async ( ) function renewManyByQuery dbName, collectionName, myQuery, newValue const await useNewUrlParser true const await console "number of documents updated:" The code defining the query and new values would look like this: newQuery = { : }; newValue = { : { : }}; renewManyByQuery( , , newQuery, newValue); let price '$10' let $set price '$20' await 'dishesdb' 'dishes' This will update the price on dishes 1 and 3 from $10 to $20. 4. Deleting Documents from a MongoDB Database , so this is the last function we’ll look at. As with creating, reading and updating, we can delete one document or multiple ones with and . The D in CRUD stands for Deletion deleteOne() deleteMany() To delete a single item from our menu, in this case the item with the innerId value 1, we’ll first add this function to our server.js file: { client = MongoClient.connect(url, { : }); obj = client.db(dbName).collection(collectionName).deleteOne(myQuery); .log( , obj.result.n); client.close(); } async ( ) function removeOneByQuery dbName, collectionName, myQuery const await useNewUrlParser true const await console "document deleted:" Then we’ll call the function like this: myQuery = { : }; removeOneByQuery( , , myQuery); let innerId 1 await 'dishesdb' 'dishes' Just like deleting one document we can delete many. Here’s the function to delete all documents that fit the given query: { client = MongoClient.connect(url, { : }); obj = client.db(dbName).collection(collectionName).deleteMany(myQuery, newValue); .log( , obj.result.n); client.close(); } async ( ) function removeManyByQuery dbName, collectionName, myQuery const await useNewUrlParser true const await console "document(s) deleted:" In this case we’ll call the function without specifying any query so calling the function will delete ALL documents in the dishes collection: removeManyByQuery( , , {}); await 'dishesdb' 'dishes' With these commands, we’ve covered pretty much all you need to know to use MongoDB with Node.js. The next step (once you’ve grabbed something quick to eat to satisfy the munchies we just gave you) is adding a frontend and Express.js to interconnect your app with the backend we just created. With those in place, you’ll be able to expand the Dinner we cooked into a web app with visuals and UX to make a user salivate.