31,19 €
Advanced Node.js Development is a practical, project-based book that provides you with all you need to progress as a Node.js developer. Node is a ubiquitous technology on the modern web, and an essential part of any web developer’s toolkit. If you're looking to create real-world Node applications, or you want to switch careers or launch a side-project to generate some extra income, then you're in the right place. This book was written around a single goal: turning you into a professional Node developer capable of developing, testing, and deploying real-world production applications.
There's no better time to dive in. According to the 2018 Stack Overflow Survey, Node is in the top ten for back-end popularity and back-end salary. This book is built from the ground up around the latest version of Node.js (version 9.x.x). You'll be learning all the cutting-edge features available only in the latest software versions.
This book delivers advanced skills that you need to become a professional Node developer. Along this journey you'll create your own API, you'll build a full real-time web app and create projects that apply the latest Async and Await technologies. Andrew Mead maps everything out for you in this book so that you can learn how to build powerful Node.js projects in a comprehensive, easy-to-follow package designed to get you up and running quickly.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 689
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Acquisition Editor:Ben Renow-ClarkeContent Development Editor:Monika SangwanTechnical Editor:Gaurav GavasCopy Editor:Tom JacobProject Coordinator:Suzanne CoutinhoProofreader: Safis EditingIndexer:Rekha NairProduction Coordinator:Shantanu N. Zagade
First published: March 2018
Production reference: 1290318
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78839-393-5
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Andrew Mead is a full-stack developer living in beautiful Philadelphia! He launched his first Udemy course in 2014 and had a blast teaching and helping others. Since then, he has launched three courses with over 21,000 students and over 1,900 5-star reviews.
Andrew currently teaches Node.js, Gulp, and React. Before he started teaching, he created a web app development company. He has helped companies of all sizes launch production web applications to their customers. He has had the honor of working with awesome companies such as Siemens, Mixergy, and Parkloco. He has a Computer Science degree from Temple University, and he has been programming for just over a decade. He loves creating, programming, launching, learning, teaching, and biking.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Advanced Node.js Development
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the author
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Getting Set Up
Installing MongoDB and Robomongo for Linux and macOS
Installing MongoDB and Robomongo for Windows
Creating and reading data
Summary
MongoDB, Mongoose, and REST APIs – Part 1
Connecting to MongoDB and writing data
Creating a directory for the project
Connecting the mongodb-connect file to the database
Adding a string as the first argument
Adding the callback function as the second argument
Error handling in mongodb-connect
Running the file in the Terminal
Adding data to the database
Adding a new record into a collection
The ObjectId
The _id property in the context of MongoDB
Calling the .getTimestamp function
Using object destructuring ES6
Creating a new instance of objectID
Fetching data
Fetching todos in Robomongo file
The find method
Writing a query to fetch certain values
Writing a query to fetch completed todos
Qureying todos by id
Implementing the count method
Querying users collection
Setting up the repo
Deleting documents
Exploring methods to delete data
The deleteMany method
The deleteOne Method
The deleteOne method
The findOneAndDelete method
Using the deleteMany and findOneAndDelete methods
Removing duplicate documents
Targeting the documents using ID
Running the findOneAndDelete and deleteMany statements
Making commit for the deleting documents methods
Updating data
Summary
MongoDB, Mongoose, and REST APIs – Part 2
Setting up Mongoose
Setting up root of the project
Connecting mongoose to database
Creating the todo model
Creating a brand-new Todo
Saving the instance to the database
Running the Todos script
Creating a second Todo model
Validators, Types, and Defaults
Mongoose validators
Customizing the Todo text property
Mongoose defaults
Mongoose types
Creating a Mongoose user model for authentication
Setting up the email property
Installing Postman
Making an HTTP request to Google
Illustrating working of the JSON data
Resource Creation Endpoint - POST /todos
Refactoring the server.js file to create POST todos route
Configuring the Todo and Users file
Loading Todo and User file in server.js
Configuring the Express application
Configuring the POST route
Getting body data from the client
Creating an instance of Mongoose model
Setting up HTTP status code
Testing POST /todos inside of Postman
Adding more Todos to the database
Testing POST /todos
Installing npm modules for testing POST /todos route
Setting up the test files
Loading the test files
Adding describe block for the test cases
Making the POST requests via supertest 
Making assertions about the POST request
Making a request to fetch the Todos from the database
Adding the catch call for the error handling
Setting up test scripts in package.json
Adding testing life cycle method in server.test.js file
Running the test suite
Test case: should not create todo with invalid body data
Making assertions about the length of the Todos collection
Making commit for POST /todos route
List Resources - GET /todos
Creating the GET /todos route
Testing the GET /todos route 
Setting up Post request to create a todo
Testing GET /todos
Adding seed data for the GET /todos test case
Adding a describe block to the test case
Adding assertions to the test case
Summary
MongoDB, Mongoose, and REST APIs – Part 3
Mongoose queries and ID validation
Todo.find method
Todo.findOne method
Todo.findById method
Handling situations where the ID doesn't exist
Validating an ObjectID
Getting an individual resource – GET /todos/:id
Taking on the challenge
Challenge step 1 - filling the code
Challenge step 2 - Making the query
challenge step 3 - success path
Testing GET /todos/:id
 Writing test cases for GET/todos/:id
Test 1 - Super test request
Test 2 - Verifying invalid ID
Test 3 - Validating invalid ObjectID
Deploying the API to Heroku
Creating a Heroku app
Heroku logs
Postman environments
Managing Postman environments
Todo App Local environment
Todo App Heroku environment
Deleting a resource – DELETE /todos/:id
Todo.remove method
Todo.findOneAndRemove method
Todo.findByIdAndRemove method
Creating a delete route
Testing DELETE /todos/:id
Test case 1 - should remove a todo
Test case 2 - should return 404 if todo not found
Test case 3 - should return 404 if object id is invalid 
Test case 4 - should return 404 if todo not found
Updating a Resource - PATCH /todos/:id
Installing Lodash library
Testing Todos for the patch call
Testing PATCH /todos/:id
Test 1 -  To complete the incomplete todo
Test 2 - to make complete todo incomplete
Creating a Test database
Summary
Real-Time Web Apps with Socket.io
Creating a new web app project
Setting up our basic app structure
Setting up the index.html file for DOCTYPE
Setting up the server.js file for the public directory
The join method
Configuring basic server setup
Setting up a gitignore file
Making a commit with the current uncommitted files
Adding Socket.io to an app
Setting up Socket.io
Creating a server using the http library
Configuring the server to use Socket.io
Communication between the client and server
The io.on method
Adding a connection event in the client
The disconnect event
Emitting and listening to custom events
Creating custom events inside an application
Moving the JavaScript into a separate file
Adding a newEmail custom event
The emit method
Testing the newEmail event
Adding a createEmail custom event
socket.emit in the developer console
The custom events in the chat app
The newMessage event
Broadcasting events
Wiring up the createMessage listener for all users
Testing the messaging events
Committing and deploying messaging to Heroku
Testing messaging in a Firefox browser using Heroku
Broadcasting events to other users
Emitting two events when a user connects
Greeting an individual user
Broadcasting a new user in the chat
Testing the user connection
Summary
Generating newMessage and newLocationMessage
Message generator and tests
Generating the newMessage object using the utility function
Writing test cases
Adding the test-watch script
Adding the test script
Running the test suite for the message utility
Integrate the utility function into our application
Event acknowledgements
Setting up acknowledgements
Sending an acknowledgement from server to the client
Updating the event emitter
Updating the event listener
The message form and jQuery
Using the jQuery library
Adding the form field in index.html
Setting up the form tag
Adding the text field
Testing the form's rendering
Using jQuery to select element
Adding the selector element to index.js
Testing the update event listener
Rendering incoming messages to the screen
Creating an ordered list to render messages
Using jQuery to create element in index.js
Testing the incoming messages
Making a commit for the message form
Geolocation
Adding the Send Location button to the application
Adding a click listener to the Send Location button
Checking access to the geolocation API
Fetching a user's position
Adding the coordinates object in the users position
Passing coordinates data with the connected users
Rendering clickable link in place of text coordinates
Sorting out the URL structure
Emitting newLoactionMessage
Adding generateLocationMessage in the message.js file
Adding an event listener for newLocationMessage
Adding test case for generateLocationMessage
Adding variables for the test case
Making assertion for generateLocationMessage
Running the test case for generateLocationMessage
Summary
Styling Our Chat Page as a Web App
Styling the chat page
Storing the template styles
Tweaking the structure for alignment
Making user experience improvements
Changing the form submit listener
Updating the input tag
Customizing the Send Location
Updating the button text
Timestamps and formatting with Moment
Timestamps in Node
The Date object
Using Moment for timestamps
The Moment documentation
Formatting date using Moment
The Manipulate section in Moment
Printing message timestamps
Getting the formatted values back from timestamps
Updating the message.js file
Integrating Moment on client
Updating the newMessage property
Updating the newLocationMessage property
Mustache.js
Adding mustache.js to the directory
Creating and rendering template for newMessage
Implementing the Mustache.js rendering method
Getting all the data showing up
Providing a custom structure
Adding the list item tag
Adding the message body tag
Creating template for the newLocation message
Rendering the newLocation template
Autoscrolling
Running a height properties calculation
Creating a new variable to scroll messages to the bottom
Determining the calculation
Taking into account the height of new message
Testing the calculations
Scrolling a user when necessary
Committing the calculation-related changes
Summary
The Join Page and Passing Room Data
Adding a join page
Updating the HTML file
Adding the head tag in the HTML file
Adding the body tag in the HTML file
Adding the form-fields for the chat page
Committing the changes in index.html
Passing room data
Getting data to the server
The params and deparams
Setting up listener in server.js
Defining the isRealString function
Calling the isRealString function in server.js
Adding error handler case in chat.js
Adding test cases for the new validation function
Test case 1 – should reject non-string values
Test case 2 – should reject string with only spaces
Test case 3 – should allow strings with non-space characters
Socket.io rooms
Targeting the specific user
Testing the specific user set up
Summary
ES7 classes
Storing users with ES6 classes – Part I
The ES6 class syntax
Creating the ES6 class for a person
The constructor function
The method function
Adding the users class
Adding the test case for addUser
Adding new instances in the users.test file
Making the assertions for the users call
Running the addUser test case
Adding the removeUser, getUser, and getUserList methods
Adding seed data for the test file
Filling the getUserList
Adding test case for getUserList
Filling the getUser
Test case – should find user
Test case – should not find user
Filling the removeUser method
Test case – should remove a user
Test case – should not remove user
Wiring up user list
Adding People list in the chat room
Adding jQuery to update the DOM
Adding user to the user's list
Adding users with unique ID
Emitting the event to the clients
Testing the users list in the chatroom
Removing users when they leave the chatroom
Updating the users list when someone left the chatroom
Emitting custom message
Rendering the users name to the chatroom
Adding a jQuery to add the users to the list
Rendering the updated People list
Testing the users name in the chatroom
Making a commit for updated users list
Sending messages to room only
Updating the chat.js and server.js files
Emitting event to the individual room
Wiring up createLoactionMessage for individual room
Committing the individual room changes
New feature ideas
Summary
Async/Await Project Setup
Using async/await features in promises
Setting up the getUser project
The array find method
Running the getUser object test
Setting up the getGrades project
Creating grades for the getGrades project
Returning a new promise
Setting up the getStatus project
Resolving the getStatus string
Calculating the average
Returning the template string
Async/await basics
Using the async function
Rejecting an error using the async function
Using the await function
A real-world example
Creating a currency-converter using the async/await function
Exploring APIs for currency exchange rate
Taking advantage of axios inside our application
The getExchangeRate function
The getCountries function
Creating convertCurrencyAlt as the async/await function
Handling errors and awaiting async function
Converting getExchangeRate and getCountries into the async function
Error handling in the async function
Printing an error to the screen
Error handling for the getExchangeRate function
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Welcome to Advanced Node.js Development. This book is packed with a ton of content, projects, challenges, and real-world examples, all designed to teach you Node by doing. This means you'll be getting your hands dirty early on in the upcoming chapters writing some code, and you'll be writing code for every project. You will be writing every line of code that powers our applications. Now, we would require a text editor for this book.
All the projects in the book are fun to build and they were designed to teach you everything required to launch your own Node app, from planning to development and testing to deploying. Now, as you launch these different Node applications and move through the book, you will run into errors, which is bound to happen. Maybe something doesn't get installed as expected, or maybe you try to run an app and instead of getting the expected output, you get a really long obscure error message. Don't worry, I am there to help. I'll show you tips and tricks to get pass through those errors in the chapters. Let's go ahead and get to it.
This book targets anyone looking to launch their own Node applications, switch careers, or freelance as a Node developer. You should have a basic understanding of JavaScript in order to follow this book.
Chapter 1, Getting Set Up, will be a very basic setup for your local environments. We'll learn to install MongoDB and Robomongo.
Chapter 2, MongoDB, Mongoose, and REST APIs – Part 1, will help you learn how to connect your Node applications to the MongoDB database you've been running on your local machine.
Chapter 3, MongoDB, Mongoose, and REST APIs – Part 2, will help you start playing with Mongoose and connect to our MongoDB database.
Chapter 4, MongoDB, Mongoose, and REST APIs – Part 3, will resolve queries and ID validation after playing with Mongoose.
Chapter 5, Real-Time Web Apps with Socket.io, will help you learn in detail about Socket.io and WebSockets, help you and create real-time web applications.
Chapter 6, Generating newMessage and newLocationMessage, discusses how to generate text and gelocation messages.
Chapter 7, Styling Our Chat Page as a Web App, continues our discussion on styling our chat page and make it look more like a real web application.
Chapter 8, The Join Page and Passing Room Data, continues our discussion about the chat page and look into the join page and passing room data.
Chapter 9, ES7 classes, will help you learn the ES6 class syntax and using it creating user's class and some other methods.
Chapter 10, Async/Await Project Setup, will walk you through the process of learning how async/await works.
To run the projects in this book, you will need the following:
The latest version of Node.js (9.x.x at the time of writing this book)
Express
MongoDB
Mongoose
Atom
We'll see the rest of the requirements along the course of the book.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Advanced-Node.js-Development. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: http://www.packtpub.com/sites/default/files/downloads/AdvancedNode.jsDevelopment_ColorImages.pdf.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."
A block of code is set as follows:
html, body, #map { height: 100%; margin: 0; padding: 0}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
[default]exten => s,1,Dial(Zap/1|30)exten => s,2,Voicemail(u100)
exten => s,102,Voicemail(b100)
exten => i,1,Voicemail(s0)
Any command-line input or output is written as follows:
$ cd css
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel."
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
In this chapter, you'll get your local environment set up for the rest of the book. Whether you're onmacOS, Linux, or Windows, we'll install MongoDB and Robomongo.
More specifically, we'll cover the following topics:
MongoDB and Robomongo installation for Linux and macOS
MongoDB and Robomongo installation for Windows
This section is for macOS and Linux users. If you are on Windows, I have written a separate section for you.
The first thing we'll do is to download and set up MongoDB, as this will be the database we will use. We'll be using a third-party service to host our database when we eventually deploy it to Heroku, but on our local machine we'll need to download MongoDB so that we can start up a database server. This will let us connect to it via our Node applications to read and write data.
In order to grab the database, we'll head over to mongodb.com. Then we can go to the Download page and download the appropriate version.
On this page, scroll down and select Community Server; this is the one we'll be using. Also, there are options for different operating systems, whether it's Windows, Linux, macOS, or Solaris. I'm on macOS, so I'll use this download:
If you're on Linux, click on Linux; then go to the Version drop down and select the appropriate version. For example, if you're on Ubuntu 14.04, you can download the correct one from the Linux tab. Then, you can simply click on the Download button and follow along.
Next you can open it up. We'll just extract the directory, creating a brand new folder in the Downloads folder. If you're on Linux, you might need to manually extract the contents of that archive into the Downloads folder.
Now this folder contains a bin folder, and in there we have all of the executables that we need in order to do things such as connecting to the database and starting a database server:
Before we go ahead and run any of them. We'll rename this directory to mongo and then move it into the user directory. You can see that now in the user directory, I have the mongo folder. We'll also create a brand new directory alongside of mongo called mongo-data, and this will store the actual data inside of the database:
So when we insert a new record into the Todos table, for example, that will live in the mongo-data folder. Once you have the mongo folder moved into the user directory and you have the new mongo-data folder, you are ready to actually run the database server from Terminal. I'll go into Terminal and navigate into that brand new mongo folder that is in the user directory, where I currently am, so I can cd into mongo, then I'll cd into the bin directory by tacking it on right there:
cd mongo/bin
From here, we have a bunch of executables that we can run:
We have things such as bisondump and mongodump. In this section, we'll focus on:mongod, which will start up the database server, andmongo, which will let us connect to the server and run some commands. Just like when we typenodewe can run some JavaScript commands right in Terminal, when we typemongo, we'll be able to run some Mongo commands to insert, fetch, or do anything we like with the data.
First up though, let's start up the database server. I'll use ./ to run a file in the current directory. The file we'll run is called mongod; also, we do need to provide one argument: the dbpath argument. The dbpath argument will get set equal to the path of the directory we just created, the mongo-data directory. I'll use ~ (the tilde) to navigate to the user directory, and then to /mongo-data, as shown here:
./mongod --dbpath ~/mongo-data
Running this command will start up the server. This will create an active connection, which we can connect to for manipulating our data. The last line that you see when you run the command should be, waiting for connections on port 27017:
If you see this, it means that your server is up and running.
Next up, let's open a new tab, which starts in the exact same directory, and this time around, instead of running mongod, we'll run the mongo file:
./mongo
When we run mongo, we open up a console. It connects to the database server we just started, and from here, we can start running some commands. These commands are just to test that things are working as expected. We'll be going over all of this in detail later in this section. For now though, we can access db.Todos, and then we'll call .insert to create a brand new Todo record. I'll call it like a function:
db.Todos.insert({})
Next, inside of insert, we'll pass in our document. This will be the MongoDB document we want to create. For now, we'll keep things really simple. On our object, we'll specify one attribute, text, setting it equal to a string. Inside of quotes, type anything you want to do. I'll say Film new node course:
db.Todos.insert({text: 'Film new node course'})
With your command looking just like this, you can press enter, and you should get back a WriteResult object with an nInserted property, which is short for the number inserted: a value set to 1. This means that one new record was created, and that is fantastic!
Now that we've inserted a record, let's fetch the record just to make sure that everything worked as expected.
Instead of calling insert, we'll call find without any arguments. We want to return every single item in the Todos collection:
db.Todos.find()
When I run this, what do we get? We get one object-looking thing back:
We have our text attribute set to the text that we provided, and we have an _id property. This is the unique identifier for each record, which we'll talk about later. As long as you're seeing the text property coming back to what you set, you are good to go.
We can shut down the mongo command. However, we will still leave the mongod command running because there's one more thing I want to install. It's called Robomongo, and it's a graphic user interface for managing your Mongo database. This will be really useful as you start playing around with Mongo. You'll be able to view the exact data saved in the database; you can manipulate it and do all sorts of stuff.
Over in Finder, we have our mongo-data directory, and you can see that there is a ton of stuff in here. This means that our data was successfully saved. All of the data is in this mongo-data directory. To download and install Robomongo, which is available for Linux, Windows and macOS, we'll head over to robomongo.org and grab the installer for our operating system:
We can click on Download Robo 3T and download the most recent version; it should automatically detect your OS. Download the installer for either Linux or macOS. The one for macOS is really simple. It's one of those installers where you take the icon and drag it into the Applications folder. For Linux, you'll need to extract the archive and run the program in the bin directory. This will start up Robomongo on your Linux distribution.
Since I'm using macOS, I'll just quickly drag the icon over to Applications, and then we can play around with the program itself. Next, I'll open it up inside the Finder. When you first open up Robomongo, you might get a warning like the following on macOS, since it's a program that we downloaded and it's not from an identified macOS developer:
This is fine; most programs you download from the web will not be official since they did not come from the App Store. You can right-click on the downloaded package, select Open, and then click on Open again to run that program. When you first open it, you'll see some screens like the following:
We have a little screen in the background and a list of connections; currently that list is empty. What we need to do is to create a connection for our local MongoDB database so that we can connect to it and manipulate that data. We have Create. I'll click on this, and the only thing we'll need to update is Name. I'll give it a more descriptive name, such as Local Mongo Database. I'll set Address to localhost and the 27017port iscorrect; there's no need to change these. So, I'll click onSave:
Next, I'll double-click on the database to connect to it. Inside the tiny window, we have our database. We are connected to it; we can do all sorts of things to manage it.
We can open up the test database, and in there, we should see one Collections folder. If we expand this folder, we have our Todos collection, and from there, we can right-click on the collection. Next, click on View Documents, and we should get our one Todo item, the one that we created over inside the Mongo console:
I can expand it to view the text property. Film new node course shows up:
If you're seeing this, then you are done.
The next section is for Windows users.
If you're on Windows, this is the installation section for you. If you're on Linux or macOS, the previous section was for you; you can skip this one. Our goal here is to install MongoDB on our machines, which will let us create a local MongoDB database server. We'll be able to connect to that server with Node.js, and we'll be able to read and write data to the database. This will be fantastic for the Todo API, which will be responsible for reading and writing various Todo-related information.
To get started, we'll grab the MongoDB installer by going over to mongodb.com. Here we can click on the big green Download button; also, we can see several options on this page:
We'll use Community Server and for Windows. If you go to the Version drop down, none of the versions there will look right for you. The top one is what we want: Windows Server 08 R2 64-bit and later with SSL support. Let's start to download this. It is slightly big; just a tad over 100 MB, so it will take a moment for the download to begin.
I'll start it up. It's one of those basic installers, where you click on Next a few times and you agree to a license agreement. Click on the Custom option for a second, although we will be following through with the Complete option. When you click on Custom, it will show you where on your machine it's going to be installed, and this is important. Here, you can see that for me it's on C:\Program Files\MongoDB\Server, then in the 3.2 directory:
This is going to be important because we'll need to navigate into this directory in order to start up the MongoDB server. I will go back though, and I will be using the Complete option, which installs everything we need. Now we can actually start the installation process. Usually, you have to click on Yes, verifying that you want to install the software. I'll go ahead and do that, and then we are done.
Now once it's installed, we'll navigate into Command Prompt and boot up a server. The first thing we need to do is to navigate into that Program Files directory. I'm in Command Prompt. I recommend that you use Command Prompt and not Git Bash. Git Bash will not work for starting up the MongoDB server. I'll navigate to the root of my machine using cd/, and then we can start navigating to that path using the following command:
cd Program Files/MongoDB/Server/3.2
This is the directory where MongoDB was installed. I can use dir to print out the contents of this directory, and what we care about here is the bin directory:
We can navigate into bin using cd bin, and print its contents out using dir. Also, this directory contains a whole bunch of executables that we'll use to do things such as starting up our server and connecting to it:
The first executable we'll run is this mongod.exe file. This will start our local MongoDB database. Before we can go ahead and run this EXE, there is one more thing we need to do. Over in the generic File Explorer, we need to create a directory where all of our data can be stored. To do this, I'll put mine in my user directory by going to the C:/Users/Andrew directory. I'll make a new folder, and I'll call this folder mongo-data. Now, the mongo-data directory is where all of our data will actually be stored. This is the path that we need to specify when we run the mongod.exe command; we need to tell Mongo where to store the data.
Over in Command Prompt, we can now start this command. I'll run mongod.exe, passing in as the dbpath argument, the path to that folder we just created. In my case, it's /Users/Andrew/mongo-data. Now if your username is different, which it obviously is, or you put the folder in a different directory, you'll need to specify the absolute path to the mongo-data folder. Once you have that though, you can start up the server by running the following command:
mongod.exe --dbpath /Users/Andrew/mongo-data
You'll get a long list of output:
The only thing you need to care about is that, at the very bottom, you should see waiting for connections on port 27017. If you see this, then you are good to go. But now that the server is up, let's connect to it and issue some commands to create and read some data.
To do this, we'll open up a second Command Prompt window and navigate into that same bin directory using cd/Program Files/MongoDB/Server/3.2/bin. From here, we'll run mongo.exe. Note that we're not running the mongod command; we're running mongo.exe. This will connect to our local MongoDB database, and it will put us in sort of a Command Prompt view of our database. We'll be able to issue various Mongo commands to manipulate the data, kind of like we can run Node from Command Prompt to run various JavaScript statements right inside the console. When we run this, we're going to connect to the database. Over in the first console window, you can see that connection accepted shows up. We do have a new connection. In the first console window now, we can run some commands to create and read data. Now I don't expect you to take away anything from these commands. We'll not talk about the ins and outs of MongoDB just yet. All I want to do is to make sure that when you run them, it works as expected.
To get started, let's create a new Todo from the console. This can be done via db.Todos, and on this Todos collection, we'll call the .insertmethod.Also, we'll callinsertwith one argument, an object; this object can have any properties we want to add to the record. For example, I want to set atextproperty. This is the thing I actually need to do. Inside quotes, I can put something. I'll go withCreate new Node course:
db.Todos.insert({text: 'Create new Node course'})
Now when I run this command, it will actually make the insert into our database and we should get a writeResult object back, with an nInserted property set to 1. This means that one record was inserted.
Now that we have one Todo in our database, we can try to fetch it using db.Todos once again. This time, instead of calling insert to add a record, we'll call find with no arguments provided. This will return every single Todo inside of our database:
db.Todos.find()
When I run this command, We get an object-looking thing where we have a text property set to Create new Node course. We also have an _id property. The _id property is MongoDB's unique identifier, and this is the property that they use to give your document; in this case, a Todo, a unique identifier. We'll be talking more about _id and about all of the commands we just ran, a little later. For now, we can close this using Ctrl + C. We've successfully disconnected from Mongo, and now we can also close the second Command Prompt window.
Before we move on, there is one more thing I want to do. We'll be installing a program called Robomongo—a GUI for MongoDB. It will let you connect to your local database as well as real databases, which we'll be talking about later. Also, it'll let you view all the data, manipulate it and do anything you could do inside a database GUI. It's really useful; sometimes you just need to dive into a database to see exactly what the data looks like.
In order to get this started, we'll head over to a new tab and go to robomongo.org:
Here we can grab the installer by going to Download. We'll download the latest version, and I'm on Windows. I want the installer, not the portable version, so I'll click on the first link here:
This is going to start a really small download, just 17 MB, and we can click on Next a few times through this one to get Robomongo installed on our machines.
I'll start the process, confirming installation and clicking on Next just a couple of times. There's no need to do anything custom inside the settings. We'll run the installer with all of the default settings applied. Now we can actually run the program by finishing all the steps in the installer. When you run Robomongo, you'll be greeted with a MongoDB Connections screen:
This screen lets you configure all of the connections for Robomongo. You might have a local connection for your local database, and you might have a connection to a real URL where your actual production data is stored. We'll get into all that later.
For now, we'll click on Create. By default, your localhostaddressand your27017portdo not need to be changed:
All I'm going to do is to change the name so that it's a little easier to identify. I'll go with Local Mongo Database. Now, we can save our new connection and actually connect to the database by simply double-clicking on it. When we do that, we get a little tree view of our database. We have this test database; this is the one that's created by default, which we can expand. Then we can expand our Collections folder and see the Todos collection. This is the collection we created inside the console. I'll right-click on this and go to View Documents. When I view the documents, I actually get to view the individual records:
Here, I see my _id and text properties that have Create new Node course sitting in the above image.
If you are seeing this, then this means that you have a local Mongo server running, and it also means that you've successfully inserted data into it.
In this chapter, you downloaded and ran the MongoDB database server. This means that we have a local database server we can connect to from our Node application. We also installed Robomongo, which lets us connect to our local database so that we can view and manipulate data. This comes in handy when you're debugging or managing data, or doing anything else with your Mongo database. We'll be using it throughout the book, and you'll begin to see why it's valuable in the later chapters. For now though, you are all set up. You are ready to continue on and start building the Todo API.
In this chapter, you're going to learn how to connect your Node applications to the MongoDB database you've been running on your local machine. This means that we'll be able to issue database commands right inside of our Node apps to do stuff like insert, update, delete, or read data. This is going to be critical if we're ever going to make that Todo REST API. When someone hits one of our API endpoints, we want to manipulate the database, whether it's reading all of the Todos or adding a new one. Before we can do any of that though, we have to learn the basics.
To connect to our MongoDB database from inside of Node.js, we're going to be using an npm module created by the MongoDB team. It's called node-mongodb-native, but it includes all of the features you'll need to connect to and interact with your database. To get to it, we're going to Google node-mongodb-native:
The GitHub repo, which should be the first link, is the one we want—the node-mongodb-native repository—and if we scroll down, we can take a look at a few important links:
First up we have documentation, and we also have our api-docs; these are going to be critical as we start exploring the features that we have inside of this library. If we scroll down further on this page, we'll find a ton of examples on how to get started. We'll be going through a lot of this stuff in this chapter, but I do want to make you aware of where you can find other resources because the mongodb-native library has a ton of features. There are entire courses dedicated to MongoDB, and they don't even begin to cover everything that's built-in to this library.
We're going to be focusing on the important and common subset of MongoDB that we need for Node.js apps. To get started, let's go ahead and open up the documentations, which are shown in the preceding image. When you go to the docs page, you have to pick your version. We'll be using version 3.0 of the driver, and there's two important links:
The
Reference
link:
This includes guide-like articles, things to get you started, and other various references.
The
API
link:
This includes the details of every single method available to you when you're working with the library. We'll be exploring some of the methods on this link as we start creating our Node Todo API.
For now though, we can get started by creating a new directory for this project, and then we're going to go ahead and install the MongoDB library and connect to the database we have running. I am going to assume that you have your database running for all the sections in this chapter. I have it running in a separate tab in my Terminal.
If you're on Windows, refer to the instructions in the Windows installation section to start your database if you forget. If you're on a Linux or macOS operating system, use the instructions I have already mentioned, and don't forget to also include that dbpath argument, which is essential for booting up your MongoDB server.
To kick things off, I'm going to make a new folder on the Desktop for the Node API. I'll use mkdir to create a new folder called node-todo-api. Then, I can go ahead and use cd to go into that directory, cd node-todo-api. And from here, we're going to run npm init, which creates our package.json file and lets us install our MongoDB library. Once again, we're going to be using enter to skip through all of the options, using the defaults for each:
Once we get to the end we can confirm our selections, and now our package.json file is created. The next thing we're going to do is open up this directory inside of Atom. It's on the Desktop, node-todo-api. Next up, inside of the root of the project we're going to create a new folder, and I'm going to call this folder playground. Inside of this folder, we'll store various scripts. They're not going to be scripts related to the Todo API; they'll be scripts related to MongoDB, so I do want to keep them in the folder, but I don't necessarily want them to be part of the app. We'll use the playground folder for that, like we have in the past.
In the playground folder, let's go ahead and make a new file, and we'll call this file mongodb-connect.js. Inside of this file, we're going to get started by loading in the library and connecting to the database. Now in order to do that, we have to install the library. From the Terminal, we can run npm install to get that done. The new library name is mongodb; all lowercase, no hyphens. Then, we're going to go ahead and specify the version to make sure we're all using the same functionality, @3.0.2. This is the most recent version at the time of writing. After the version number, I am going to use the --save flag. This is going to save it as a regular dependency, which it already is:
npm install [email protected] --save
We're going to need this to run the Todo API application.
For the first argument in our case, we're going to start off with mongodb://. When we connect to a MongoDB database, we want to use the mongodb protocol like this:
MongoClient.connect('mongodb://')
Next up, it's going to be at localhost since we're running it on our local machine, and we have the port, which we have already explored: 27017. After the port, we need to use / to specify which database we want to connect to. Now, in the previous chapter, we used that test database. This is the default database that MongoDB gives you, but we could go ahead and create a new one. After the /, I'm going to call the database TodoApp, just like this:
MongoClient.connect('mongodb://localhost:27017/TodoApp');
Next up, we can go ahead and provide the callback function. I'm going to use an ES6 arrow (=>) function, and we're going to get past two arguments. The first one is going to be an error argument. This may or may not exist; just like we've seen in the past, it'll exist if an error actually happened; otherwise it won't. The second argument is going to be the client object. This is what we can use to issue commands to read and write data:
MongoClient.connect('mongodb://localhost:27017/TodoApp', (err, client) => { });
Inside the Terminal, we can run the file using node playground as the directory, with the file itself being mongodb-connect.js:
node playground/mongodb-connect.js
When we run this file, we get Connected to MongoDB server printing to the screen:
If we head over into the tab where we have the MongoDB server, we can see we got a new connection: connection accepted. As you can see in the following screenshot, that connection was closed down, which is fantastic:
Using the Mongo library we were able to connect, print a message, and disconnect from the server.
Now, you might have noticed that we changed the database name in the MongoClient.connect line in Atom, and we never actually did anything to create it. In MongoDB, unlike other database programs, you don't need to create a database before you start using it. If I want to kick up a new database I simply give it a name, something like Users.
Now that I have a Users database, I can connect to it and I can manipulate it. There is no need to create that database first. I'm going to go ahead and change the database name back to TodoApp. If we head into the Robomongo program and connect to our local database, you'll also see that the only database we have is test. The TodoApp database was never even created, even though we connected to it. Mongo is not going to create the database until we start adding data into it. We can go ahead and do that right now.
