Afrikaans
Akan
Albanian
Amharic
Arabic
Armenian
Azerbaijani
Basque
Belarusian
Bemba
Bengali
Bihari
Bosnian
Breton
Bulgarian
Cambodian
Catalan
Cebuano
Cherokee
Chichewa
Chinese (Simplified)
Chinese (Traditional)
Corsican
Croatian
Czech
Danish
Dutch
English
Esperanto
Estonian
Ewe
Faroese
Filipino
Finnish
Frisian
Ga
Galician
Georgian
German
Greek
Guarani
Gujarati
Haitian Creole
Hausa
Hawaiian
Hebrew
Hindi
Hmong
Hungarian
Icelandic
Igbo
Indonesian
Interlingua
Irish
Italian
Japanese
Javanese
Kannada
Kazakh
Kinyarwanda
Kirundi
Kongo
Korean
Krio (Sierra Leone)
Kurdish
Kurdish (Soranî)
Kyrgyz
Laothian
Latin
Latvian
Lingala
Lithuanian
Lozi
Luganda
Luo
Luxembourgish
Macedonian
Malagasy
Malay
Malayalam
Maltese
Maori
Marathi
Mauritian Creole
Moldavian
Mongolian
Myanmar (Burmese)
Montenegrin
Nepali
Nigerian Pidgin
Northern Sotho
Norwegian
Norwegian (Nynorsk)
Occitan
Oriya
Oromo
Pashto
Persian
Polish
Portuguese (Brazil)
Portuguese (Portugal)
Punjabi
Quechua
Romanian
Romansh
Runyakitara
Russian
Samoan
Scots Gaelic
Serbian
Serbo-Croatian
Sesotho
Setswana
Seychellois Creole
Shona
Sindhi
Sinhalese
Slovak
Slovenian
Somali
Spanish
Spanish (Latin American)
Sundanese
Swahili
Swedish
Tajik
Tamil
Tatar
Telugu
Thai
Tigrinya
Tonga
Tshiluba
Tumbuka
Turkish
Turkmen
Twi
Uighur
Ukrainian
Urdu
Uzbek
Vietnamese
Welsh
Wolof
Xhosa
Yiddish
Yoruba
Zulu
All right.
So in the previous module we looked at how we would use MongoDB in the command line through the use
of the Mongo shell.
And that's pretty much MongoDB in its purest form in an isolated setting. But that's no use to us because
we want to build applications that have databases
right?
So we need to learn how to integrate all MongoDB database with on Node.js application.
And that is what this module is all about.
Now when you're creating a Node app that needs to connect to a MongoDB database
there's essentially two options for you to choose from.
One is to use the MongoDB native driver that we're going to talk about very quickly.
Another is to use a ODM or an Object Document Mapper that's called mongoose.
Now the most popular way of working with MongoDB and Node.js is through using this package called
mongoose.
And the reason is because it vastly simplifies and cuts down on the code that's required in order to
work with your MongoDB database.
But I want to show you first how the native MongoDB driver would work and then we'll go through how
to use mongoose just so that you can see for yourself just how much easier it is to incorporate mongoose
and it makes your life as a developer so much better.
But first let's get started and take a look at how we would use the MongoDB native driver.
Firstly I want to head over to the MongoDB documentation at docs.mongodb.com.
And here we're going to head over to the tab that's called drivers. And on the left hand pane here you can
see that there's a whole bunch of drivers for different languages.
Now the driver is what's going to enable our MongoDB to interact with our application and depending on
which language your application was developed with then you'll need to use a different driver.
Now in our case we're going to choose Node.js and we're going to view the latest documentation. And from
here we're going to head over to quick starts and it details pretty much step by step how you would
get started using the native MongoDB Node.js driver.
Well that's quite a long sentence.
So essentially what we're trying to do is we're trying to glue together our MongoDB database with
our Node.js application.
And this is going to be the syntax and the code and we're going to install the driver to enable us to
do that.
First things first, we're going to need a new project. For this project
I've decided that I'm going to make a database of fruits and I'm going to rate all the fruits that I've
tried.
And there's some really wacky ones out there that I've come across through my travels and I think it's
a pretty nice way of showing you how to work with MongoDB and Node. CD over to wherever you keep
all of your development files
and then we're going to create a new directory and that's going to be called FruitsProject. And then
we're going to head over to FruitsProject
and here we're going to create a new app.
So we're going to create a new file called app.js and as per usual we're going to initialize our npm.
But this time instead if you don't want to hit enter to insert the default values when you initialize
npm, you can just add a -y which basically says yes to everything.
And when you hit enter you can see that we've initialized our npm and accepted all of the defaults.
So now all we have to do is to install the MongoDB driver.
And to do that with npm we have to install something called mongodb.
And remember we don't need the --save anymore as of the latest versions of npm.
So we can simply say npm i short for install and then it's mongodb.
Hit enter
and that should install the driver in a couple of seconds.
So now all we have to do is open up our app.js inside Atom and get started developing on your Node
JS application that integrates with a MongoDB database.
I'm just going to show you how we can get started using this by just using some the code from the getting
started guide.
So I'm simply going to copy this part and add it to our aappp.js and again we've got a whole bunch
of warnings so let's just silence that from //jshint. And
now I want to walk you through this code. First
we are requiring a package called mongodb
and along with that package we also insert another one called assert.
Now everything that you see that is related to assert be it on
Node.js applications or iOS applications,
it's always to do with testing.
And so you'll see that when we add a lot of the MongoDB code into our application, there's a lot of
assert that just validates our data entry and our connection to the MongoDB database.
Now the next part is the connection URL. And you can see this looks a little bit similar to what
we've been using to develop websites on our local system.
The important thing to note here is that when you're working with MongoDB the port that they use is
pretty much always 27017
and this is just some sort of arbitrary number that they've decided upon.
This is the base URL for connecting to our database. And then we specify a database name
so let's change it to fruitsDB and then we create a new Mongo client which is going to connect to
our MongoDB database and if a fruitsDB doesn't exist then it will create it.
And if all of that happened without any errors then we are going to log that we have connected successfully
to the server. Once we're done
we're going to close the connection to our database
and this is all that this code does so far, the majority of it down here is just to create a new connection
to a new database.
And this is equivalent to when we saw in the Mongos shell previously where we just said use fruits
DB that use fruitsDB if we wanted to use it in our Node.js application using the MongoDB native driver
is basically all of this code.
So it's a bit crazy.
And the reason why I'm walking you through this and explaining the code is that in reality most developers
who are working with Node and MongoDB will rarely use the native MongoDB driver.
Now it's not because it's no good,
it works and allows a lot of personalization and you can drill down to the specifics and you can set
up and use your MongoDB database with a high level of control.
All right so now that we have created this, let's go ahead and run our app.js using again node app
.js and you can see we get a error. And it says MongoNetworkError failed to connect to server.
And whenever you get this, you always have to remind yourself
do you still have the Mongo server up and running?
So create a new tab and remember whenever we're using MongoDB we always have to first run our server
using the command mongod. And only once it's done running and it's waiting for connections on again
that port 27017
it's going to come up in a lot of places.
Well now we're ready to actually connect to our database and we can run node ap.js again
and now we are successfully connected to the server.
If at some point you get a deprecation warning as you see here then just read what the message says
because MongoDB, because it's relatively new,
they will add new syntax and new code and new APIs, new ways of doing things, on a regular basis.
So in this case it says deprecation warning current URL string parser is deprecated and will
be removed in a future version. To use the new parser, pass option
this to the MongoClient.connect.
If you didn't know what to do with this deprecation warning, then what do you do?
Well you just copy it in its entirety and then you paste it into Google and see what does Google say.
So first link is a link to Stack Overflow and it already tells you this is how you would work around
it.
So you can either change to a local version of Mongo which is not what we want to do, we want to work with
the latest version.
So if you do indeed want to use latest version, then you will have to make your connection using this
use
NewUrlParser key value pair.
And here they've got some example code of how you would add it.
So they've added it to MongoClient.connect.
You can see that even though we're taking the code from MongoDB using the latest version of their
documentation stuff gets out of date and it's really important that you don't get fazed by every little
thing that you see in the console and simply just Google for an answer.
Let's go back to Atom and let's go ahead and fix this.
We're going to change our Mongo client to use the URL that we specified for our MongoDB server
but then we're going to add a comma and we're going to paste in that option that they wanted us to add.
So there we go.
Now let's hit save and let's rerun our app.
You can see now we get connected successfully to server and we don't get any deprecation warnings.
Even though the last time we did get this warning our app is still running and connected successfully
so it didn't actually affect our app.
But it's important that whenever you see a deprecation warning to just copy and paste it into Google
and see what the existing solutions are.
It's very very rare that you will be coming across a problem for the first time and you're the only
person with that problem.
It almost never happens.
OK so now that we have it connected successfully to our Mongo server the next part is adding some
data to our database.
So how do we do that?
Well it's back to the documentation and the next part is of course insert a document.
So let's copy all of this code from the documentation and let's paste it below the last line that we
have.
So this code what it does is it will create a new collection and the collection that we're going to
create is going to be called fruits.
We've got a collection called fruits inside our fruitsDB
And this is equivalent to when we used our new database and then we said db.fruits.insert.
And then we get to insert some data in here. The data is in the same format as we saw before.
It's a bunch of key value pairs and here they're inserting three items into a field called a
and then they've added the values 1,2 ,3.
So as we saw before in the Mono shell whenever you see a pair of curly brackets that's going to be
an individual document or an individual record.
And in our case we're going to insert three fruits.
So I'm going to just paste in some code that I wrote a little bit earlier on and we'll just format this
or that you can see it more clearly.
So here I'm inserting three documents and each document is a fruit.
So the first one has a name of apple, a score of 8
and a review of 'great fruit'. And the rest of them are for orange and banana.
So we're now creating this array of fruits and we're using the method insertMany which comes from MongoDB
to insert all of these three documents into a collection called fruits inside a database called
fruitsDB.
And down here you can see that the next few lines are dedicated to validation.
So they've added a whole bunch of asserts.
And if we go through them line by line, this one says validate to make sure that there are no errors
when we inserted our document.
And the next ones ensure that we have three results that are inserted into our collection.
And if that is so then we're going to log inserted three documents into the collection. And the next
part is to simply run that function inside our insert documents function and they show you that client.
connect should now look like this
with this additional part. Up here inside client.connect instead of calling client.close we're
going to paste that new code which calls insertDocuments and only once it's done inserting the documents
do we close the connection to our database.
So now let's hit save and let's again run our code with node app.js and you can see we've successfully
connected to the server and we've inserted three documents into the collection.
And you can actually test out the validation quite easily. Say if we were only to add 2 records to
our database, then you will get an assertion error saying that 3 doesn't equal 2.
Well you only inserted 2 items but I was expecting 3.
So you're ready beginning to see the validation that we can place inside our app.js using the Mongo
DB driver in order to validate the data that we're inserting.
And you can see just how very flexible all of these asserts are. If I head into my command line and I
create a new terminal and then I tap into the Mongo shell and I say show dbs, you can see now in
addition to our shopDB which we created inside the Mongo shell we've also got this new database
called fruitsDB and that one was not created using the Mongo shell but instead from Node.js
using the MongoDB driver.
And that's where the fruitsDB got created.
And now if I say use fruitsDB then we can say show collections inside this db
so we have this collection called fruits and that of course comes from this part
when we created our new collection using the db.collection method. And then we inserted a whole
bunch of data
if you're a member so we should be able to say db.fruits.find.
And we're going to leave the parentheses empty to show us all the data that we currently have. The keen
eyed amongst you will spot that we have 5 records instead of what you might expect to be 3 because
the first time we added apple, orange, banana and the second time we deleted the banana record and we
got an assertion failure.
Now assertion is quite a complex topic but in this case this is a nonfatal assertion.
So one actually prevent the insertion of these records but it simply alerts you to the fact that the
assertion has failed.
So the next step is how do we get our app.
js to find all of these records? How do we read our data inside our Node.js app?
Well it's only a short scroll away.
So the next part is find all documents and let's just go ahead and add this into our code
right at the bottom again and this section we have to specify the collection where we want to find something
from which if you remember earlier on was called fruits,
so let's change that to fruits. And then it's going to look through the collection and it's going to
find all.
And then it's going to save it into an array
and for that array we need to have some fruits. And in the callback
we're going to get back the object that we got from the find function and we're going to log those fruits
into the console.
Now if we hit save and call that find function inside again the client.connect,
in this case we're not going to insert any more documents.
We're simply just going to find our documents.
So I'm just going to copy that part of the code and we're going to update this method
client.connect to delete the insertion method call and just find those records inside our database.
Let's head back to our terminal connection where we've got our prompt and let's call node app.
js again.
So now you can see that we've found the following records and this printed in here is an array of Javascript
objects and you can see it looks very similar to what we've got in the Mongo shell but what's logged
here are actually the documents from our MongoDB
but here we've actually got our Javascript objects.
So if we now have access to these living Javascript objects inside an array in our app.js then we
can use our Javascript code and Node.js to do whatever it is that we wish with it.
As you can see this code is very very wordy and there's a lot of it that's just boilerplate code that
you have to add every single time you use the native MongoDB driver.
And for some people especially if you want to develop applications quickly it can be a bit of a pain.
So in the coming modules I want to show you what most Node developers will work with which is a module called
mongoose and it will vastly simplify the code that we have here and we will walk through how to use
mongoose to make your life developing Mongo and node apps so much easier.
So I'll see you there.
Can't find what you're looking for?
Get subtitles in any language from opensubtitles.com, and translate them here.