This nodejs MongoDB tutorial explores how to select, insert, update and delete records from MongoDB database. MongoDB is a free and open source NoSQL database management system. It stores data as JSON key-value pairs. Connect, Save and Find Data in MongoDB with NodeJS and ExpressJS. There is also a MongoDB driver, I’ll tell you about it in this article, but I prefer to use the Mongoose because it provides the opportunity to create the database schema After successful install packages, in project folder create server.js file and in your terminal or command prompt run MongoDB with mongod command.
By Last Updated: 7th Aug 2019Posted In:This tutorial has been tested with,. It will not work properly with older versions on some systems.This tutorial was originally published on and does not include a video component.Updated February 1, 2019! IntroductionThere are approximately one hundred million tutorials on the web for getting a 'Hello, World!' App running with Node.js.
This is great! It's especially great if your goal is to greet the world and then give up on your web career and go spend the rest of your life as, like, a jockey or something. That doesn't really describe most of us, so we go looking for more tutorials.In my experience, the 'next level' tutorials out there seem about 30 levels further along. We go from 'Hello, World!' To building out an entire blogging system with comments. Which is also great, but a lot of times those tutorials assume the reader has done a whole bunch of intermediate fiddling, and they often drop a bunch of big functions on you all at once. I tend to learn best by making lots of smaller, intermediate steps, and I don't think I'm the only one.I'm not the only one, right?Well, I've done the fiddling and read a bunch of tutorials and shouted at my command prompt until things finally worked.
I have a web project up and running which uses Node.JS, the Express framework, the EJS HTML pre-processor, and MongoDB for data. I can read to and write from the DB. From there, the sky's the limit.Here's the deal: I'm going to show you how to get all of this stuff set up. I'll be assuming that you're a front-end developer who knows HTML5/CSS3/JavaScript well enough that I don't have to explain those.
If that's you, then this should be a solid primer.Your app will look pretty, it will connect to a DB, it'll get some results, and it'll do stuff with those results. Then for kicks we'll also make it save data to the DB.
Through it all, I will explain what the code does, and how to write it, instead of just giving you massive functions to stare at. We'll go from nothing even installed, to a DB-driven web app written in a language you fully understand, and the foundation necessary to build additional functionality into your app. And we'll do it in about 60 minutes of installation and coding time. Is that awesome?
I submit that it is.Let's go. Part I – 15 minutes of installingIf you're really starting from scratch, then getting everything up and running takes a little bit of time. None of it is difficult.
I run Windows 10 on my main machine, so it'll be slightly different for those on a Mac or Ubuntu or other.nix system, but it's principally the same thing in all cases. Step 1 – Install Node.jsThis is really easy. Hit the and click the big green Install button for the LTS (long-term-stable) version.
It'll detect your OS and give you the appropriate installer. Run the installer. That's it, you have installed Node.js and, equally important, NPM, which lets you add all kinds of great stuff to Node quickly and easily. Open a command prompt. cd to the directory in which you wish to keep your test apps(for the purposes of this tutorial, C:node).Step 2 – Install Express GeneratorNow that we have Node running, we need the rest of the stuff we're going to actually use to create a working website. To do that we're going to install Express, which is a framework that takes Node from a barebones application and turns it into something that behaves more like the web servers we're all used to working with (and actually quite a bit more than that).
We need to start with Express-Generator, which is actually different than Express itself it's a scaffolding app that creates a skeleton for express-driven sites. In your command prompt, type the following. Command C:nodeC:nodenpm install -g express-generatorThe generator should auto-install, and since it (like all packages installed with -g) lives in your master NPM installation directory, it should already be available in your system path. So let's use our generator to create the scaffolding for a website. Step 3 – Create an Express ProjectWe're going to use Express and EJS, but not the Stylus CSS preprocessor (which people sometimes use in this stack). We're just going to use straight CSS for right now.
We have to use EJS or another templating engine to gain access to our Node/Express-based data. EJS's not hard to learn if you already know HTML, since it's just HTML with some embedded JavaScript. Express defaults to Jade, but we're not using that because a) it's deprecated in favor of the new version, which is called Pug, and b) it's indentation-based and I don't like indentation-based markup. It's too easy for one accidental extra tab or space to break your whole page.A quick note on indentation: everything is this tutorial has been normalized to 2-space indents because that's become standard in the JavaScript world. If you want to use four spaces, or actual tabs, that's just fine by me.Anyway, still in c:node or wherever you're storing your node apps, type this.
Command C:nodenodetest1C:nodenodetest1npm install -save monk@^6.0.6 mongodb@^3.1.13This will add those two dependencies to our package.json file (you can switch back to your text editor to check). It'll also install them for use in our app but right now those are the only two dependencies we've installed, because there's an important step when getting set up with Express that we haven't done yet. Step 5 – Install DependenciesNow we've defined our dependencies and we're ready to go. Note that new versions of NPM modules are frequently rolled out. The versions listed in this tutorial are proven to work; if you go with the latest versions, I'm afraid you're on your own.Return to your command prompt and type this. Command C:nodenodetest1C:nodenodetest1npm installThat will read the JSON file and install all the stuff listed in the dependencies object that aren't yet installed (yes, including Express – we installed the generator globally, but we still have to install the actual module inside this one particular project). You might get a few vulnerability warnings depending on versions, but you can ignore them.
We're not deploying this anywhere, so security's not really a concern. Anyway, at the time of the 'last updated' date above, there are zero known vulnerabilities in the project.Once NPM has run its course, you should have a nodemodules directory which contains all of our dependencies for this tutorial. This will also create a file called package-lock.json which you can ignore completely. It's important, but only if you're an experienced Node developer building production-level apps. You now have a fully-functioning app ready and waiting to run, so let's test out our web server!
Type the following. C:nodenodetest1app.jsvar createError = require('http-errors');var express = require('express');var path = require('path');var cookieParser = require('cookie-parser');var logger = require('morgan');var indexRouter = require('./routes/index');var usersRouter = require('./routes/users');This creates a bunch of basic JavaScript variables and ties them to certain packages, dependencies, node functionality, and routes.
Routes are kind of like controllers in this setup – they direct traffic and also contain some programming logic (you can establish a more traditional MVC architecture with Express if you like. That's outside of the scope of this article). Back when we set up this project, Express created all of this stuff for us. We're going to totally ignore the user route for now and just work in the top level route (controlled by c:nodenodetest1routesindex.js). C:nodenodetest1app.jsmodule.exports = app;A core part of Node is that basically all modules export an object which can easily be called elsewhere in the code. Our master app exports its app object.Now then, let's make stuff.
We're not going to just stick 'Hello, World!' On our index page. Instead we're going to use this as an opportunity to learn a bit more about routes and to take a look at how EJS works for putting pages together.We're going to start by adding a new app.use directive to app.js. Find the section that looks like this. C:nodenodetest1app.jsapp.use('/', indexRouter);app.use('/users', usersRouter);These directives are telling Express what route files to use. Now, normally I'd advocate setting up separate route files for different parts of your app.
For example, the users route file might contain routes for adding users, deleting them, updating them, and so forth, while a new route file called 'locations' might handle adding, editing, deleting and displaying location data (in an app for which that was required). In this case, to keep things simple, we're going to do everything in the index router. That means you can completely ignore the /users line.Remember that the Express scaffolding already defined the routes variable and pointed it at the index router.
We're going to add a helloworld method to that router which will render a different page than the default. In your text editor, open up your routes folder, find index.js, and open it. It will look like this. Command C:nodenodetest1npm startIn order to restart the server. By the way, this seems a good time to mention: changes to EJS templates do not require a server restart, but basically whenever you change a js file, such as app.js or the route files, you'll need to restart to see changes.SO with the server restarted, navigate to and enjoy the completely asinine text that gets displayed:OK!
So now we've got our router routing us to our view, which we are viewing. Let's do some modeling. I'll give you a moment if you need to fix your hair or makeup.
Part 3 – Create our DB and read stuff from it Step 1 – Install MongoDBWe're breaking this up into two parts: Windows and Mac. We'll do Windows first.WindowsWe're leaving our text editor for a bit and going back to our command prompt. Well, first we're going to our web browser, pointing it to and downloading Mongo. You don't want the 'try free' button, which is going to push their enterprise server or cloud server on you, neither of which you need for local development. Instead, hover over 'products' and click 'MongoDB Server' - this will take you to the Community Server download page. It will auto-detect your OS and give you the appropriate download link.Click the download button and run the installer.
![]()
If you're on Windows, it'll offer to install a GUI called Compass. You can do that if you want, but we won't be using it in this tutorial. It'll also ask if you want to register MongoDB as a service. The answer is 'yes' because it makes everything else a lot easier. The DB server will just run in the background whenever your machine is on (using minimal resources, don't worry) and you won't need to start it up every single time.Once it's installed, you're all set.MacIf you're on OSX, it's a little more complicated to set MongoDB up as a background service, but it can be done. I recommend using Homebrew to do the installation.
If you're not familiar with Homebrew, that's OK. It comes with OSX and you don't really need to do anything to configure it.
Head for your terminal and type the following. Mongo ConsoleMongoDB shell version v4.0.5connecting to: mongodb://127.0.0.1:27017MongoDB server version: 4.0.5Server has startup warnings:a bunch of warnings that you can ignore for this tutorialPossibly an annoying ad for their cloud serviceAll right, you've got MongoDB up and running, and you've connected to it with the client. We'll use this client to manually work on our database, for a bit, but it's not necessary for running the website. Only the server daemon (mongod) is needed for that. Step 3 – Create a DatabaseThe first thing we're going to do is create a database in which to store stuff. In your Mongo console, type the following. Mongo Consoleuse nodetest1Now we're using the database 'nodetest1,' which is great except nothing actually exists yet.
To make the database exist, we have to add some data. We're going to start off by doing that right inside of the Mongo client. Step 4 – Add some DataMy favorite thing about MongoDB is that it uses JSON for its structure, which means it was instantly familiar for me.
If you're not familiar with JSON, you'll need to do some reading, as I'm afraid that's outside the scope of this tutorial.Let's add a record to our collection. For the purposes of this tutorial, we're just going to have a simple database of usernames and email addresses. Our data format will thus look like this. Testuser1testuser2testuser3I know this isn't rocket science, but that's the point. We're just doing a simple DB read-and-write in this tutorial, not trying to build a whole website.
![]()
First things first, we need to add a few lines to our main app.js file—the heart and soul of our app—in order to actually connect to our MongoDB instance. Open C:nodenodetest1app.js and at the top you'll see. C:nodenodetest1app.jsvar createError = require('http-errors');var express = require('express');var path = require('path');var cookieParser = require('cookie-parser');var logger = require('morgan');// New Codevar monk = require('monk');var db = monk('localhost:27017/nodetest1');These lines tell our app we want to talk to MongoDB, we're going to use Monk to do it, and our database is located at localhost:27017/nodetest1. Note that 27017 is the default port your MongoDB instance should be running on. If for some reason you've changed it, obviously use that port instead. Now look further down in the file, where you have this. C:nodenodetest1app.jsapp.use('/', indexRouter);app.use('/users', usersRouter);We need to do some work here.
Those app.use statements (along with the others you'll find in app.js) are establishing middleware for Express. The short, simple explanation is: they're providing custom functions that the rest of your app can make use of. It's pretty straightforward, but due to chaining it needs to come before our route definitions, so that they can make use of it.Above the two lines just mentioned, add the following.
Command C:nodenodetest1C:nodenodetest1npm startNow open your browser and head to and marvel at the results.You're now pulling data from the DB and spitting it out onto a web page. Nice!There one more thing I badly wanted to cover in this tutorial, but because it's already about as long as the Bible, I'm going to breeze through it here. You could very easily change your userlist view from an Express-driven web page complete with EJS template to a plain old JSON response. You could then access this with AJAX and manipulate it on the client-side, with jQuery for example, instead of on the server side. In fact, I wanted to cover that so badly that I wrote an entire second tutorial on it. You can find the link at the end of this one!Let's finish this up.
Part 4 – The holy grail: writing to the DBWriting to the database is not particularly difficult. Essentially we need to set up a route that takes a POST, rather than a GET. Step 1 – Create your data inputWe're going quick and dirty here: two ugly, unstyled text inputs and a submit button. 1996-style, but before we get to that, we're going to do some javacripting. Let's start by quickly wiring up a route for our add user form. Open /routes/index.js and add the following code above the last module.exports line. C:nodenodetest1viewsnewuser.ejs
Under that we've defined our two inputs and our button.If you restart your node server and go to you'll see your form in all its glory.Go ahead and submit. Enjoy the 404 error.
We're about to fix that. Step 2 – Create your DB functionsOK, this is pretty much the same process as with the user list. We don't need another app.use statement since we've already wrapped our database object into every request (see above).
That means it'll be accessible to any new routes we write. That means that all we need to do is add a route for POSTing to /adduser.Go back to /routes/index.js and let's create our insertion function. Once again, you'll want to put this above the final module.exports line (it doesn't REALLY matter, but it makes things cleaner to wrap up with the export). This is a big one, so I've commented the code pretty thoroughly. Command C:nodenodetest1C:nodenodetest1npm startAssuming your server is running, which it should be, return to your web browser and point it at again. There's our exciting form, just like before.
Except now let's fill in some values before we hit submit. I went with username 'noderocks' and email '[email protected]' you can go with whatever you'd like.Click submit, and check it out we're back at /userlist and there's our new entry!We are officially reading and writing from a MongoDB database using Node.js, Express, and EJS. You are now what the kids call a 'full stack' developer (probably not a GOOD one, just yet, but I didn't promise that).Congratulations.
If you followed this all the way through, and if you really paid attention to what you were doing and didn't just paste code, you should have a really solid grasp on routes and views, reading from the DB, and posting to the DB. That is all you need to get started developing whatever app you want to build. I don't know about you, but I think that's really cool.
Part 5 – Next steps. New: Express.js Cheat SheetLooking for a handy reference for Express? I've put together a beautiful cheat sheet full of commands, along with a bunch of other great resources. Click the button below to learn more!The 'sequel' to this tutorial is now available! Find it at:.From here, there's a million different directions you could go.
I recommend completing the tutorial mentioned above, or you could dive into our, which will step you through building and deploying a barebones web application using a custom Express.js API and a React front-end.I hope this tutorial's been helpful. I wrote it because I could've used it when I got started, and I couldn't seem to find something that was quite at this level, or that broke things down in such long, long, loooong detail. If you made it this far, thanks for sticking with it!© 2018 CloseBrace™, LLC.Visit Us:.
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. 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).
Comments are closed.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |