In this video you're going to connect to your Mongo DB database from a node j s application and you're
going to learn how to insert new documents into the database.
Now to get all of this done we'll be using the Mongo D.B. native driver.
This is nothing more than an NPR module we're going to install and it's going to allow us to interact
with our database from node before we actually install anything.
I want to take a quick moment to pull up this module in the Web so you know where it lives and you know
where you can learn more to kick things off.
Let's head over to the browser and explore this native driver.
I'm going to close the two tabs I had open in the installation videos and to kick things off.
We'll be heading over to the Mongo DB home page at Mongo D.B. dot com.
Here we're looking for their documentation section up top.
We have docs and once we're out the documentation we're looking for docs about their Mongo DB drivers
which is in the sidebar just a few items down.
The drivers are the libraries that allow you to interact with the Mongo DB database from a wide range
of programming languages down below.
They have native drivers for about a dozen or so different languages.
We have Si we have Java node HP Python Ruby and others.
I'm going to go ahead and click node j s to find the native drivers for the platform we're using now
right here.
The most recent release is three point one of the driver and there are two links for the documentation.
There's the reference which contains more tutorials and guides about how to use features.
This is essentially what we're going to cover in the videos anyways but there is importantly the API
documentation.
This contains documentation for every single property function or method available with the driver.
We'll be referring back to the documentation here and there as we explore new features.
So we'll leave the docs up though I'll close the other page.
The Mongo D.B. home page and the last thing we're gonna pull out before we move into visual studio code
is the NPM module.
PAGE You can google NPM Mongo D.B. to find the package the package name is Mongo D.B..
This is the official native driver released by the Mongo D.B. company.
So down below it's a very popular module with about a million weekly downloads and it contains some
basic instructions for getting started and also links over to the documentation which we actually already
have open down below.
There's other information about getting started though we're gonna work through all of that right now.
So let's go ahead and create a new project.
Get this installed and use it to insert some documents into the database to do this we're going to navigate
over to visual studio code and we're going to open up a second terminal tab.
We want to leave the database running the database needs to be running in order for us to connect to
it so we don't want to shut this down.
I'm going to click that plus button to open up a new tab.
So right here I now have two.
One is running Mongo D.B..
And that's going to stay as is for the duration of this project and the other.
This is where we're gonna run application commands like npm install or node to start up our app first
up let's go ahead and create a directory where we can put all of the code right here.
I'm going to create a new folder and I'll call this one task manager.
Now once we have the task manager directory in place I want to use C D to navigate into that directory
so I can initialize NPM and I can install the module CDE task manager once we're in the task manager
directory.
We're gonna use NPM in it with the Y flag to generate the package.
Jason File using all of the defaults.
Right here it has been created and we can see it inside of our project route.
From there we're going to install the new module we want to use NPM ie Mongo D.B. at three point one
point one zero.
I'm gonna run the installation command which will generate the node modules directory and from here
we're actually ready to use the driver to connect to our database and insert some documents.
Now the task manager app is going to have a lot more code in the future and we're going to have a nice
advanced directory structure to stay organized for the moment.
We really just need a single script as we start to play around with Mongo D.B. right here.
I'm going to create a mongo D.B. dot J.S. file and we're gonna use this file to explore all of those
operations we want to be able to support.
So we want to figure out how we can perform all of the crud operations crud it stands for Create read
update and delete.
We need to be able to perform all of these operations to be able to manage our data successfully.
Let's get started by importing the module we just installed down below a new constant Mongo D.B. which
is going to store whatever comes back from requiring the Mongo D.B. NPM library and what comes back
is an object.
Now on that object there's one thing we need to actually initialize the connection.
This is known as the Mongo client.
So we're going to create a new constant for that Mongo uppercase M client and we'll get that off of
Mongo D.B. dot once again uppercase M Mongo uppercase C client the Mongo client is gonna give us access
to the function necessary to connect it to the database so we can perform our four basic CRUD operations.
Now before we actually get into the connection side of things we have to define the connection U.R.L.
in the database we're trying to connect to and I'm going to do that using two variables.
I'll have one be a constant connection you are L which will equal a string will fill the value out in
just a moment and we're going to have a second one as well database once again this will also be a string
and we'll fill that value out in a second.
Now for the connection U.R.L. we want to connect to that local host server that's up and running in
our first terminal tab devalue we have to provide for that is the following.
It starts off with Mongo D.B. colon forward slash forward slash we're using their protocol then from
there it would be the IP address 1 2 7 0 0 1 followed by the port which would be a colon and the default
port we know is 2 7 0 1 7.
Now you might be wondering why I'm typing out the local host IP instead of literally typing out local
host.
That's because local host has known to cause some really strange issues where it slows down your application
and things start to fail.
We're not exactly sure why that is all we know is that when we type out the entire IP that issue doesn't
happen and the application works as expected.
So I definitely recommend using the full IP right here as it won't cause problems later in the class.
Next up the database name we can pick whatever we want for this.
I'm gonna go ahead and use task hyphen manager if the data is for my task manager app a database name
of task manager it seems appropriate enough now that we have this in place we have all of the information
we need to actually connect to our database.
Actually I'm gonna change this from database to database name to be a little more explicit about what
exactly is being stored inside of there.
From here we can now use Mongo client to connect to the server Mongo client has one method we're gonna
end up using that is appropriately called Connect and connect takes in quite a few different arguments
to actually set up the connection.
The first is the connection you are El.
Now I already have that stored in a variable so I can simply reference connection you are all right
here to use the following value that is the value we're trying to use then as the second argument we're
going to provide an options object right here we're gonna be setting up a single option which is use
new you are Rel parser we're gonna set this to true.
So the U R L parser that was originally used by default is being deprecated and required to pass in
this option in order for argue our ls to be passed correctly so we can actually connect to the server
so that is arguments won and arguments do.
The last argument we're going to pass to the Connect function is going to be a callback function.
The callback function is gonna get called when we're actually connected to the database so connecting
to the database it is not a synchronous operation.
It is indeed asynchronous it's going to take a bit of time to get that connection set up and the callback
function will run when the Connect operation is complete.
Now it could either fail or succeed and you're gonna get access to different arguments depending on
what happens in this callback is gonna get called with either an error or with a client.
If the first argument exists that means things went wrong and it will contain an error message describing
why it couldn't connect.
If the second argument exists that means things went well and you're now connected to the server and
you can start to manipulate your databases inside of the callback function.
The first thing we're gonna do is handle any potential errors that occurred.
Let's start with an if statement to check if an error occurred right here.
If one did we're just going to use console dot log to print a message to the console and we'll say something
like unable to connect to database perfect.
Now the code below is only going to run if the connection actually worked.
So to prevent this code from running when an error occurs I'm gonna use return right here to stop the
function execution.
So if an error occurs we print the message and I use return it simply to stop the function from continuing
to execute.
That's going to ensure that the code down below only runs when things went well.
And what are we going to do for the moment.
We'll just use console log to print a message connected correctly.
Perfect.
If we see this we know things went wrong.
If we see this we know things went well.
Now let's go ahead and save the file and try to connect from the terminal.
I'm going to go ahead and execute our node script that's going to be node space Mongo D.B. dot J S I'm
going to run it.
And what do we get.
Right here I get connected correctly which is fantastic.
That means we were able to connect to our Mongo D.B. server using Node J.
S Now before we go any further with the code in this file.
I want to switch over to the other terminal tab where our Mongo DB server is running and you'll notice
that down below we're gonna end up getting information about the connections that come and go.
So right here I see connection accepted from.
And then the following IP and port.
So this is letting us know that someone did indeed connect to the database.
Now it's important to note that at times you'll only have one connection but you'll see a message saying
you have five or six open connections.
That's because when we connect with Mongo D.B. it uses a connection pool.
So there's actually more connections that are opened behind the scenes even though we've only called
Connect once that makes sure that our node J.S. application can still communicate quickly even if we're
trying to perform a lot of operations at the same time.
So now over in the second tab where we're running our node app you'll notice that it's still hanging
it hasn't brought us back to the command prompt and that's because once the connection is opened your
node process is going to stay up and running as long as you let it.
Or as long as that connection remains active we can always close the connection and shut down the node
process by using control C from the terminal.
So there we go.
We successfully connected to the database.
Now it's time to insert our very first document.
I'll be removing this console dot log call and replacing it with some other code.
The first thing we need to do is get a reference to the specific database we want to manipulate.
In this case we chose the name task manager.
Now with Mongo D.B. there's no need to create this database using Mongo D.B. or using the gooey rowboat
3 T simply by picking a name and accessing it.
Mongo D.B. will automatically create it for us.
So right here what I do is use client dot D.B..
This takes as its one and only argument the name of the D.B..
You're trying to manipulate in our case we stored that name in the database name variable and what it
gives you back is a database reference typically stored in a variable called D.B. which we can now use
to manipulate that database.
Once again no need to create that simply using it in the code is enough.
Now we know that with our no rescue l databases like Mongo D.B. we don't have tables we have collections.
The next thing we need to do before we can insert a document is figure out which collection we're trying
to insert the document into.
We can use collections to track all of the distinct things in our application.
We can have a collection for users a collection for tasks and a collection for anything else we might
need to track.
We're gonna go ahead and insert a single document into a user's collection.
To do that we use D.B. dot collection and collection is a function so we'll call it as such and it expects
the name of the collection you're trying to manipulate.
In this case let's go ahead and use users.
From here we can go ahead and call a method on that collection reference to insert a document.
This is insert one insert one expects an object as that first argument and this should contain all of
the data you're trying to insert for the moment.
Let's go ahead and just put in two fields about us we'll make ourselves the first user I'll set name
equal to my first name.
And I'm also going to set age equal to my age.
And there we go.
We're going to insert a very simple document into that user's collection.
Now that we have this in place let's go ahead and save Mongo D.B. dot J.
S and from terminal down below.
I'm gonna use clear to clear the terminal output.
Now let's go ahead and run our script once again node Mongo D.B..
Dot J S.
And once again it's still going to hang out even though the operation has been completed.
We're not seeing any messaging at all which is a good thing.
The only message we would ever see is if things went wrong.
Now to actually ensure that our data was inserted correctly we can use robo three T.
That is the whole point of that administration tool.
So let's go ahead and head over there to view our data.
I'm going to crack open robo 3 ti which is still connected to that local Mongo DB database connection.
We set up and the last video I'm going to close both open tabs the Welcome tab and the one tab we used
to run a command in the last video to test the connection from here what I'm going to do is right click
that connection and click refresh and you'll notice we have a brand new database showing up called Task
Manager which matches up perfectly with the database name we chose inside of our code.
Now if we actually crack that open we can view the collections for task manager.
And what do we have.
We have a single collection users and users that matches up perfectly with the name we chose for our
collection right here on line 16 of our JavaScript file.
Now we can actually look at the data stored inside of there simply opening it up is not enough.
We have to right click that collection and then we can click view documents.
When we do that it's going to grab all of the documents stored in that collection and it's going to
dump them to the gooey interface.
Right here we have a single document and if we expand that we can view the data stored inside of it.
We have three fields two of which we created.
I have the name field with the value Andrew and I have the age field with the value twenty seven.
Now you'll notice this third field underscore I.D. which we did not create under score I.D. store is
a unique identifier for that particular document.
And this is not something that's unique to mongo D.B..
If you've used Eskew own databases before like my S Q Well you know you have that I.D. column with the
auto incrementing integer which goes from one to two to three to four as you add new records into a
table with Mongo D.B..
We also have an I.D. property but it's stored on underscore I.D. This is a unique identifier for the
particular document allowing us to identify it.
Now we'll talk more about the value and what exactly an object I.D. is.
As we progressed through the section for now all you need to know is that when you insert a document
it's going to have a unique identifier automatically generated for us.
And that's a good thing.
Now from here we can explore some other ways we can view our data in robo 3 T up here on the top right.
We are currently in the tree view.
We could also switch over to the table view to view our data in a more traditional table.
We also have a couple of other views we have text mode which is not particularly useful.
Typically I'll stick with either the tree view or the table view.
So now that we have one document in place it's time to move on to the next video where we're going to
continue to explore how we can insert data.
And there's also going to be a challenge where you're gonna have to insert data into a new collection
on your own.
Let's take a quick moment to recap what we did in this video.
We installed the Mongo D.B. NPM library.
This is a native driver created by the Mongo DB company allowing us to connect to a Mongo DB database
from node j s.
Here we used the Connect method to connect to this specific server and we use the D.B. method on client
to get the connection for these specific database.
From there we were able to insert our one document and view it over inside of robo three T.
Let's go ahead and continue on to the next video and continue to explore insertions.