All right. 1
So in the previous module we looked at how we would use MongoDB in the command line through the use 2
of the Mongo shell. 3
And that's pretty much MongoDB in its purest form in an isolated setting. But that's no use to us because 4
we want to build applications that have databases 5
right? 6
So we need to learn how to integrate all MongoDB database with on Node.js application. 7
And that is what this module is all about. 8
Now when you're creating a Node app that needs to connect to a MongoDB database 9
there's essentially two options for you to choose from. 10
One is to use the MongoDB native driver that we're going to talk about very quickly. 11
Another is to use a ODM or an Object Document Mapper that's called mongoose. 12
Now the most popular way of working with MongoDB and Node.js is through using this package called 13
mongoose. 14
And the reason is because it vastly simplifies and cuts down on the code that's required in order to 15
work with your MongoDB database. 16
But I want to show you first how the native MongoDB driver would work and then we'll go through how 17
to use mongoose just so that you can see for yourself just how much easier it is to incorporate mongoose 18
and it makes your life as a developer so much better. 19
But first let's get started and take a look at how we would use the MongoDB native driver. 20
Firstly I want to head over to the MongoDB documentation at docs.mongodb.com. 21
And here we're going to head over to the tab that's called drivers. And on the left hand pane here you can 22
see that there's a whole bunch of drivers for different languages. 23
Now the driver is what's going to enable our MongoDB to interact with our application and depending on 24
which language your application was developed with then you'll need to use a different driver. 25
Now in our case we're going to choose Node.js and we're going to view the latest documentation. And from 26
here we're going to head over to quick starts and it details pretty much step by step how you would 27
get started using the native MongoDB Node.js driver. 28
Well that's quite a long sentence. 29
So essentially what we're trying to do is we're trying to glue together our MongoDB database with 30
our Node.js application. 31
And this is going to be the syntax and the code and we're going to install the driver to enable us to 32
do that. 33
First things first, we're going to need a new project. For this project 34
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 35
tried. 36
And there's some really wacky ones out there that I've come across through my travels and I think it's 37
a pretty nice way of showing you how to work with MongoDB and Node. CD over to wherever you keep 38
all of your development files 39
and then we're going to create a new directory and that's going to be called FruitsProject. And then 40
we're going to head over to FruitsProject 41
and here we're going to create a new app. 42
So we're going to create a new file called app.js and as per usual we're going to initialize our npm. 43
But this time instead if you don't want to hit enter to insert the default values when you initialize 44
npm, you can just add a -y which basically says yes to everything. 45
And when you hit enter you can see that we've initialized our npm and accepted all of the defaults. 46
So now all we have to do is to install the MongoDB driver. 47
And to do that with npm we have to install something called mongodb. 48
And remember we don't need the --save anymore as of the latest versions of npm. 49
So we can simply say npm i short for install and then it's mongodb. 50
Hit enter 51
and that should install the driver in a couple of seconds. 52
So now all we have to do is open up our app.js inside Atom and get started developing on your Node 53
JS application that integrates with a MongoDB database. 54
I'm just going to show you how we can get started using this by just using some the code from the getting 55
started guide. 56
So I'm simply going to copy this part and add it to our aappp.js and again we've got a whole bunch 57
of warnings so let's just silence that from //jshint. And 58
now I want to walk you through this code. First 59
we are requiring a package called mongodb 60
and along with that package we also insert another one called assert. 61
Now everything that you see that is related to assert be it on 62
Node.js applications or iOS applications, 63
it's always to do with testing. 64
And so you'll see that when we add a lot of the MongoDB code into our application, there's a lot of 65
assert that just validates our data entry and our connection to the MongoDB database. 66
Now the next part is the connection URL. And you can see this looks a little bit similar to what 67
we've been using to develop websites on our local system. 68
The important thing to note here is that when you're working with MongoDB the port that they use is 69
pretty much always 27017 70
and this is just some sort of arbitrary number that they've decided upon. 71
This is the base URL for connecting to our database. And then we specify a database name 72
so let's change it to fruitsDB and then we create a new Mongo client which is going to connect to 73
our MongoDB database and if a fruitsDB doesn't exist then it will create it. 74
And if all of that happened without any errors then we are going to log that we have connected successfully 75
to the server. Once we're done 76
we're going to close the connection to our database 77
and this is all that this code does so far, the majority of it down here is just to create a new connection 78
to a new database. 79
And this is equivalent to when we saw in the Mongos shell previously where we just said use fruits 80
DB that use fruitsDB if we wanted to use it in our Node.js application using the MongoDB native driver 81
is basically all of this code. 82
So it's a bit crazy. 83
And the reason why I'm walking you through this and explaining the code is that in reality most developers 84
who are working with Node and MongoDB will rarely use the native MongoDB driver. 85
Now it's not because it's no good, 86
it works and allows a lot of personalization and you can drill down to the specifics and you can set 87
up and use your MongoDB database with a high level of control. 88
All right so now that we have created this, let's go ahead and run our app.js using again node app 89
.js and you can see we get a error. And it says MongoNetworkError failed to connect to server. 90
And whenever you get this, you always have to remind yourself 91
do you still have the Mongo server up and running? 92
So create a new tab and remember whenever we're using MongoDB we always have to first run our server 93
using the command mongod. And only once it's done running and it's waiting for connections on again 94
that port 27017 95
it's going to come up in a lot of places. 96
Well now we're ready to actually connect to our database and we can run node ap.js again 97
and now we are successfully connected to the server. 98
If at some point you get a deprecation warning as you see here then just read what the message says 99
because MongoDB, because it's relatively new, 100
they will add new syntax and new code and new APIs, new ways of doing things, on a regular basis. 101
So in this case it says deprecation warning current URL string parser is deprecated and will 102
be removed in a future version. To use the new parser, pass option 103
this to the MongoClient.connect. 104
If you didn't know what to do with this deprecation warning, then what do you do? 105
Well you just copy it in its entirety and then you paste it into Google and see what does Google say. 106
So first link is a link to Stack Overflow and it already tells you this is how you would work around 107
it. 108
So you can either change to a local version of Mongo which is not what we want to do, we want to work with 109
the latest version. 110
So if you do indeed want to use latest version, then you will have to make your connection using this 111
use 112
NewUrlParser key value pair. 113
And here they've got some example code of how you would add it. 114
So they've added it to MongoClient.connect. 115
You can see that even though we're taking the code from MongoDB using the latest version of their 116
documentation stuff gets out of date and it's really important that you don't get fazed by every little 117
thing that you see in the console and simply just Google for an answer. 118
Let's go back to Atom and let's go ahead and fix this. 119
We're going to change our Mongo client to use the URL that we specified for our MongoDB server 120
but then we're going to add a comma and we're going to paste in that option that they wanted us to add. 121
So there we go. 122
Now let's hit save and let's rerun our app. 123
You can see now we get connected successfully to server and we don't get any deprecation warnings. 124
Even though the last time we did get this warning our app is still running and connected successfully 125
so it didn't actually affect our app. 126
But it's important that whenever you see a deprecation warning to just copy and paste it into Google 127
and see what the existing solutions are. 128
It's very very rare that you will be coming across a problem for the first time and you're the only 129
person with that problem. 130
It almost never happens. 131
OK so now that we have it connected successfully to our Mongo server the next part is adding some 132
data to our database. 133
So how do we do that? 134
Well it's back to the documentation and the next part is of course insert a document. 135
So let's copy all of this code from the documentation and let's paste it below the last line that we 136
have. 137
So this code what it does is it will create a new collection and the collection that we're going to 138
create is going to be called fruits. 139
We've got a collection called fruits inside our fruitsDB 140
And this is equivalent to when we used our new database and then we said db.fruits.insert. 141
And then we get to insert some data in here. The data is in the same format as we saw before. 142
It's a bunch of key value pairs and here they're inserting three items into a field called a 143
and then they've added the values 1,2 ,3. 144
So as we saw before in the Mono shell whenever you see a pair of curly brackets that's going to be 145
an individual document or an individual record. 146
And in our case we're going to insert three fruits. 147
So I'm going to just paste in some code that I wrote a little bit earlier on and we'll just format this 148
or that you can see it more clearly. 149
So here I'm inserting three documents and each document is a fruit. 150
So the first one has a name of apple, a score of 8 151
and a review of 'great fruit'. And the rest of them are for orange and banana. 152
So we're now creating this array of fruits and we're using the method insertMany which comes from MongoDB 153
to insert all of these three documents into a collection called fruits inside a database called 154
fruitsDB. 155
And down here you can see that the next few lines are dedicated to validation. 156
So they've added a whole bunch of asserts. 157
And if we go through them line by line, this one says validate to make sure that there are no errors 158
when we inserted our document. 159
And the next ones ensure that we have three results that are inserted into our collection. 160
And if that is so then we're going to log inserted three documents into the collection. And the next 161
part is to simply run that function inside our insert documents function and they show you that client. 162
connect should now look like this 163
with this additional part. Up here inside client.connect instead of calling client.close we're 164
going to paste that new code which calls insertDocuments and only once it's done inserting the documents 165
do we close the connection to our database. 166
So now let's hit save and let's again run our code with node app.js and you can see we've successfully 167
connected to the server and we've inserted three documents into the collection. 168
And you can actually test out the validation quite easily. Say if we were only to add 2 records to 169
our database, then you will get an assertion error saying that 3 doesn't equal 2. 170
Well you only inserted 2 items but I was expecting 3. 171
So you're ready beginning to see the validation that we can place inside our app.js using the Mongo 172
DB driver in order to validate the data that we're inserting. 173
And you can see just how very flexible all of these asserts are. If I head into my command line and I 174
create a new terminal and then I tap into the Mongo shell and I say show dbs, you can see now in 175
addition to our shopDB which we created inside the Mongo shell we've also got this new database 176
called fruitsDB and that one was not created using the Mongo shell but instead from Node.js 177
using the MongoDB driver. 178
And that's where the fruitsDB got created. 179
And now if I say use fruitsDB then we can say show collections inside this db 180
so we have this collection called fruits and that of course comes from this part 181
when we created our new collection using the db.collection method. And then we inserted a whole 182
bunch of data 183
if you're a member so we should be able to say db.fruits.find. 184
And we're going to leave the parentheses empty to show us all the data that we currently have. The keen 185
eyed amongst you will spot that we have 5 records instead of what you might expect to be 3 because 186
the first time we added apple, orange, banana and the second time we deleted the banana record and we 187
got an assertion failure. 188
Now assertion is quite a complex topic but in this case this is a nonfatal assertion. 189
So one actually prevent the insertion of these records but it simply alerts you to the fact that the 190
assertion has failed. 191
So the next step is how do we get our app. 192
js to find all of these records? How do we read our data inside our Node.js app? 193
Well it's only a short scroll away. 194
So the next part is find all documents and let's just go ahead and add this into our code 195
right at the bottom again and this section we have to specify the collection where we want to find something 196
from which if you remember earlier on was called fruits, 197
so let's change that to fruits. And then it's going to look through the collection and it's going to 198
find all. 199
And then it's going to save it into an array 200
and for that array we need to have some fruits. And in the callback 201
we're going to get back the object that we got from the find function and we're going to log those fruits 202
into the console. 203
Now if we hit save and call that find function inside again the client.connect, 204
in this case we're not going to insert any more documents. 205
We're simply just going to find our documents. 206
So I'm just going to copy that part of the code and we're going to update this method 207
client.connect to delete the insertion method call and just find those records inside our database. 208
Let's head back to our terminal connection where we've got our prompt and let's call node app. 209
js again. 210
So now you can see that we've found the following records and this printed in here is an array of Javascript 211
objects and you can see it looks very similar to what we've got in the Mongo shell but what's logged 212
here are actually the documents from our MongoDB 213
but here we've actually got our Javascript objects. 214
So if we now have access to these living Javascript objects inside an array in our app.js then we 215
can use our Javascript code and Node.js to do whatever it is that we wish with it. 216
As you can see this code is very very wordy and there's a lot of it that's just boilerplate code that 217
you have to add every single time you use the native MongoDB driver. 218
And for some people especially if you want to develop applications quickly it can be a bit of a pain. 219
So in the coming modules I want to show you what most Node developers will work with which is a module called 220
mongoose and it will vastly simplify the code that we have here and we will walk through how to use 221
mongoose to make your life developing Mongo and node apps so much easier. 222
So I'll see you there.