All right. 1
So in the last lesson we looked at one way of getting our Node.js app to work with the MongoDB database. 2
And that was through the use of the native MongoDB driver. 3
You saw just how painful it was to do something very simple. 4
I mean in the Mongo shell it was like three or four lines of commands and it turned into 20, 30 lines 5
of code through using the native driver. 6
And a lot of that was down to adding in validation code and writing a lot of the boilerplate or just 7
the simple act of connecting to the MongoDB server. 8
This is why most Node developers who are working with MonoDB who use a package called Mongoose and 9
this is what's called an ODM or an Object Document 10
Mapper. What it will do is it will allow your Node.js app which speaks the language of Javascript objects 11
to be able to talk to your MongoDB database which speaks in the language of documents and collections 12
and databases. 13
And the main objective of this framework is to simplify the writing of validation code, 14
the writing of your business logic boilerplate 15
and just to make the code just shorter and easier to work with. And essentially everything that we did 16
previously using the MongoDB driver, if we were to use Mongoose, all we have to write is pretty much 17
just this right? 18
We require the mongoose package, we connect to the database and we create a new database 19
if it doesn't exist. And then we create a new model of how our data will be represented. 20
This is the only new part 21
and we're going to be going through it in detail. And then with that new model we will create a new document. 22
And then we simply just save our model into the MongoDB database. 23
So it's vastly shorter 24
and I'm going to talk through it in detail and show you how we can use it. 25
Way way back when we were working with the document object model, 26
if you remember it was quite a pain to write all of the code for the DOM. 27
But then when we started using JQuery and we started adding those dollar signs everywhere, everything 28
got a lot shorter and a lot simpler and easier to work with. 29
Well essentially Mongoose does the same job. 30
So let's go ahead and see how we can use Mongoose to make our fruits database way way simpler. 31
First things first, make sure that you've got a active MongoDB server that's running. 32
And then if you open up a Mongo shell and you say, "show dbs", you can see that we've got our fruits 33
DB already created and you can see that it's so small that it doesn't even really register a size. 34
But this time we're going to create our fruitsDB and all of the data inside 35
using just Mongoose. 36
So I'm going to actually delete that database. 37
And in the Mongo shell in order to delete an entire database, what you have to do is you first have to 38
switch to that database. 39
So you'll say use fruitsDB 40
and we've switched to this particular database. 41
And then we just say "db.dropDatabase" and then a set of parentheses to run that command 42
and now we no longer have the fruitsDB. 43
So if I say, "show dbs", you can see that it's been wiped from MongoDB server. 44
Now we're ready to head back into our app.js and we're going to modify all of this code and instead 45
of using the native MongoDB driver, we're going to use Mongoose. 46
And I'm just going to show you just how much it cuts down on our code and how much simpler and easier 47
to understand the code becomes. 48
First things first, we have to require Mongoose. 49
So I'm going to delete these two lines where we're requiring the native Mongo client and the assert 50
testing package. In our app. 51
js, we now want to use this package called Mongoose. 52
But if you remember we haven't actually installed it using NPM yet. 53
So if you head over to hyper and make sure that you are still inside your fruits project, then go ahead 54
and use npm install to install the mongoose package. 55
Once that's done then we can go ahead and move on to the next goal which is to connect to our Mongo 56
DB database. 57
Now you can see at the moment in order to do that we're taking up something like 20 lines of code and 58
some of that will be validation code and some of it will just be the simple act of connecting to the 59
database. 60
Now I want to show you just how simple all of that becomes by using Mongoose instead. 61
So we'll write mongoose.connect and then we're going to open up a set of parentheses 62
and we're going to add the URL that we want to connect to. That connection URL will look very 63
similar to what we've got here. 64
It's going to be a string that is mongodb://localhost:27017. 65
That will specify the port where we can access our MongoDB database server. 66
And then all we have to do is put another forward slash at the end of there and then we can specify 67
the name of the database that we want to create or connect to. 68
So it's going to make a connection to our MongoDB server and then it's going to look for a database 69
called fruitsDB, and if it doesn't exist, then it will create this brand new database. And that replaces 70
all of this. 71
So we can now go ahead and delete all of that. 72
And now if I hit save and we go over to our hyper terminal and use node app.js to run our app, then 73
you can see we've now started our server but we still get the same deprecation warning as we saw before. 74
Now we have to again pass this useNewUrlParser. 75
If we again copy this and paste it into Google to remind ourselves of what that solution was, 76
you can see that this person who's answered is actually very kindly included what you should do if you're 77
using Mongoose to connect to your database. 78
And this is basically what we have to do. 79
We have to add it right at the end of the connect method. 80
So let's go ahead and add that in to change our code. 81
So we've got mongoose.connect and then this is the URL you want to connect to and then we're going to 82
add that new option at the end here which is to use the new url parser and this will resolve that deprecation 83
warning. 84
So now the next thing that we want to do is to insert some data. 85
And you can see that we're doing that right now through these 20 lines. But this code is essentially 86
very similar to what we saw when we were using the Mongo shell. 87
Now I want to show you how you would do that with Mongoose because it's a little bit different from 88
what we've done so far. 89
The first thing we have to do is to create a new schema. 90
And this is basically a blueprint or the structure of our data that we're going to save into our Mongo 91
DB database. In order to do this we can create a new const that's called fruitsSchema. 92
And this is going to be equal to a new mongoose schema. 93
And then we open up a set of parentheses and inside that we add a new Javascript object, 94
so we open up our curly braces. 95
Now in this schema, we basically scaffold out how we want data in a particular collection to be structured. 96
So for example if we were creating a new fruit document, what would the structure of that data look 97
like? 98
Well it might have a name which is going to be of data type string, and then it might have maybe a rating 99
which will be a number, and then it might have just a review which will be a text review for that fruit. 100
This is what our fruit schema would look like using Mongoose 101
and this lays out the foundation for every new fruit document that will be added to our database. After 102
we create the schema, 103
we use the schema to create a Mongoose model. And we do that by saying const Fruit = mongoose 104
.model. 105
And then we specify two parameters. 106
The first one is, what is going to be the name of the collection that is going to comply with this particular 107
schema. 108
Well in our case we want to create a collection of fruits right? 109
So we'll have these fruits each as individual records or documents, they'll be saved into a collection 110
called fruits and then that will be inside our database called fruitsDB. 111
So the first parameter is always going to be a string here. 112
Now the Mongoose way of doing things is to specify the singular name of your collection. 113
So if you have a collection of fruits then inside here will be the word "Fruit" in a singular form. And 114
Mongoose will very cleverly convert this string into a pluralize form to create your collection. 115
By doing this you will have created a new collection called fruits and those fruits have to stick to 116
the structure that we've specified in the fruit schema. 117
And now and only now are we ready to create a new fruit document. 118
I'm going to create something called "fruit" with a lowercase f. 119
This is going to be a new Fruit with a capital F and this is to show that I'm creating this document 120
from this model that we specified up here which means that it's going to have to stick to this schema 121
that we laid out here as well. 122
So now this new fruit is going to have a name, let's call it Apple. 123
It's going to be an apple that we're going to save into our database. And then we're going to give it 124
a rating. 125
And I'm going to give a rating out of 10. 126
So I think Apples are decent, let's give it a 7 and then 127
let's give it a review 128
"Pretty solid" as fruit. Can't really hate on apples right? 129
And now that we've constructed our new document, all we have to do is say fruit.save. 130
And this calls the save method in Mongoose to save this fruit document into a fruit collection inside 131
our fruitsDB. And that replaces our insertDocuments method from the Mongo client. 132
So at the moment you can see that we don't have our prompt. And whenever you are in that position the 133
first thing that will save is CONTROL + C. 134
This should exit out of any process that the terminal or hyper is currently performing. 135
And in our case, it was because we still had an active connection to our MongoDB server. 136
Now let's run our app.js again to save that new fruit into our database. 137
And if I switch over to our shell then we can go ahead and say "show dbs" to show that we've now updated 138
our database with a new fruitsDB and let's say use fruitsDB and now let's see what collections 139
we have in this database. 140
So we'll say "show collections". And you can see that automatically Mongo has dropped the capsule on the 141
earth and pluralized this fruit that we specified here into a collection of fruits. 142
And it's pretty clever how it does that. Behind the scenes is actually using Lodash to achieve it. 143
We saw that in an earlier module. But essentially it allows you to specify the singular form and work 144
with the singular form. 145
But behind the scenes it will create that collection of fruits for you to be able to work with. 146
So if we say "db.fruits.find" so we show everything that's inside our fruits collection, 147
then you can see we have a single document that has an id, a name, a rating and a review. 148
Now, remember that every single time you run fruit.save it will save the same fruit into your fruits 149
collection in your fruits database. 150
So if you don't want that to happen, then you can just comment out this method call and you won't end 151
up with a whole bunch of apples in your database. 152
But it's now time for a challenge. 153
I want you to create a new collection and this is going to be a collection of people. You need to create 154
the schema for a new person and they need to have two fields: a name and an age. 155
And then you're going to create a new model from that schema of a person and you're going to create a new 156
person who's called John and he's 37. And then you're going to say that new person to our database and 157
show it using the Mongo shell. Pause the video now and complete this challenge. 158
All right. 159
So right below our fruit.save 160
we're going to use the same setup but we're going to apply it to a collection of people now. 161
So we're still connected to the same fruits database which is exactly what we want, but we're going 162
to create a new person schema. 163
And this is going to be a new Mongoose schema and it's going to specify that every person we create 164
has to have a name. 165
And they also probably should have an age. 166
So the name is going to be of data type string 167
and the age will be data type number. And then we're going to create our model of a person from this 168
schema. 169
So it's going to equal mongoose.model and then the singular form of a person is person. But behind 170
the scenes we will get a collection called people that will be created. And these people inside the collection 171
will follow the person schema. 172
Using that schema we're going to create a new person and this new person is going to have a couple of 173
values. 174
It's going to have a name of John and an age of 37. And now we can take this person that we created and 175
we can save it to our database. 176
So now if we go back to our terminal and we exit our previous database connection and we run on node 177
app.js again, we can go to our Mongo shell and confirm that if we say "show collections" we now have 178
a collection of fruits and a collection of people. 179
And as I said it's pretty clever about converting your singular form into a pluralized collection. 180
Now if we say "db.people.find" then we end up showing all the documents that we have inside our 181
people collection which, is John who's 37. 182
What if we wanted to add a bunch of fruits in bulk like we did previously using the native MongoDB 183
driver? 184
Well let's say that we create some new fruits. Let's say const we create a kiwi. And this is going to 185
be a new Fruit with a capital F and the kiwi is of course called kiwi. 186
It has a score of "10" because kiwis are awesome and has a review of "The best fruit". And then I'm just 187
going to go in and add two more fruits, orange and banana. Oranges too sour for me and bananas have a 188
really weird texture. 189
So those are three fruits. 190
And now in order to save it in bulk, we can tap into our fruit model and we can say "insertMany". 191
Now how did I know that I could use fruit. 192
insertMany? 193
Well the documentation of course. 194
So if you head over to Mongoose and click on "Read the docs" then inside the API section you can see that they've 195
got all of the methods that you can do with the model listed in here. 196
And very often when you're working with a new package you'll be reading through the documentation and 197
digging through it to see what it can do. 198
So here we have this method called Model.insertMany and it allows us to insert an array of documents 199
into a particular model or basically our collection. 200
The syntax basically looks like this. 201
You specify the name of your Mongoose model which will allow it to connect to the relevant collection 202
and also know what the schema is 203
it should work with. 204
And then we use that method 205
insertMany and it takes two parameters. 206
The first one is an array of objects that match that particular schema, 207
so all fruits here. We've got kiwi, orange and bananas. 208
So we'll add that kiwi, orange and banana. And then the second parameter will be a callback and it allows 209
us to log any errors if there were any issues with inserting all of these objects into our fruits collection. 210
And so we can check say if there's an error then we'll log the error, but else then we'll log "Successfully 211
saved all the fruits to fruitsDB". And let's close that off and let's hit save and exit out of our database 212
and run our app.js again. 213
You can see that we've got that callback, "Successfully saved all of the fruits to the fruitsDB". 214
So there were no errors 215
and if we go and check our db.fruits.find, then 216
we now have a few more fruits. 217
We've got apple, kiwi, orange and banana. 218
We've now seen how you can create new documents and new collections using Mongoose and MongoDB. But how 219
exactly do we access these items in our database through our app.js? 220
How do we get access to living objects that our app can tap into? 221
Well that's what we're going to look at in the next lesson.