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 last lesson we looked at one way of getting our Node.js app to work with the MongoDB database.
And that was through the use of the native MongoDB driver.
You saw just how painful it was to do something very simple.
I mean in the Mongo shell it was like three or four lines of commands and it turned into 20, 30 lines
of code through using the native driver.
And a lot of that was down to adding in validation code and writing a lot of the boilerplate or just
the simple act of connecting to the MongoDB server.
This is why most Node developers who are working with MonoDB who use a package called Mongoose and
this is what's called an ODM or an Object Document
Mapper. What it will do is it will allow your Node.js app which speaks the language of Javascript objects
to be able to talk to your MongoDB database which speaks in the language of documents and collections
and databases.
And the main objective of this framework is to simplify the writing of validation code,
the writing of your business logic boilerplate
and just to make the code just shorter and easier to work with. And essentially everything that we did
previously using the MongoDB driver, if we were to use Mongoose, all we have to write is pretty much
just this right?
We require the mongoose package, we connect to the database and we create a new database
if it doesn't exist. And then we create a new model of how our data will be represented.
This is the only new part
and we're going to be going through it in detail. And then with that new model we will create a new document.
And then we simply just save our model into the MongoDB database.
So it's vastly shorter
and I'm going to talk through it in detail and show you how we can use it.
Way way back when we were working with the document object model,
if you remember it was quite a pain to write all of the code for the DOM.
But then when we started using JQuery and we started adding those dollar signs everywhere, everything
got a lot shorter and a lot simpler and easier to work with.
Well essentially Mongoose does the same job.
So let's go ahead and see how we can use Mongoose to make our fruits database way way simpler.
First things first, make sure that you've got a active MongoDB server that's running.
And then if you open up a Mongo shell and you say, "show dbs", you can see that we've got our fruits
DB already created and you can see that it's so small that it doesn't even really register a size.
But this time we're going to create our fruitsDB and all of the data inside
using just Mongoose.
So I'm going to actually delete that database.
And in the Mongo shell in order to delete an entire database, what you have to do is you first have to
switch to that database.
So you'll say use fruitsDB
and we've switched to this particular database.
And then we just say "db.dropDatabase" and then a set of parentheses to run that command
and now we no longer have the fruitsDB.
So if I say, "show dbs", you can see that it's been wiped from MongoDB server.
Now we're ready to head back into our app.js and we're going to modify all of this code and instead
of using the native MongoDB driver, we're going to use Mongoose.
And I'm just going to show you just how much it cuts down on our code and how much simpler and easier
to understand the code becomes.
First things first, we have to require Mongoose.
So I'm going to delete these two lines where we're requiring the native Mongo client and the assert
testing package. In our app.
js, we now want to use this package called Mongoose.
But if you remember we haven't actually installed it using NPM yet.
So if you head over to hyper and make sure that you are still inside your fruits project, then go ahead
and use npm install to install the mongoose package.
Once that's done then we can go ahead and move on to the next goal which is to connect to our Mongo
DB database.
Now you can see at the moment in order to do that we're taking up something like 20 lines of code and
some of that will be validation code and some of it will just be the simple act of connecting to the
database.
Now I want to show you just how simple all of that becomes by using Mongoose instead.
So we'll write mongoose.connect and then we're going to open up a set of parentheses
and we're going to add the URL that we want to connect to. That connection URL will look very
similar to what we've got here.
It's going to be a string that is mongodb://localhost:27017.
That will specify the port where we can access our MongoDB database server.
And then all we have to do is put another forward slash at the end of there and then we can specify
the name of the database that we want to create or connect to.
So it's going to make a connection to our MongoDB server and then it's going to look for a database
called fruitsDB, and if it doesn't exist, then it will create this brand new database. And that replaces
all of this.
So we can now go ahead and delete all of that.
And now if I hit save and we go over to our hyper terminal and use node app.js to run our app, then
you can see we've now started our server but we still get the same deprecation warning as we saw before.
Now we have to again pass this useNewUrlParser.
If we again copy this and paste it into Google to remind ourselves of what that solution was,
you can see that this person who's answered is actually very kindly included what you should do if you're
using Mongoose to connect to your database.
And this is basically what we have to do.
We have to add it right at the end of the connect method.
So let's go ahead and add that in to change our code.
So we've got mongoose.connect and then this is the URL you want to connect to and then we're going to
add that new option at the end here which is to use the new url parser and this will resolve that deprecation
warning.
So now the next thing that we want to do is to insert some data.
And you can see that we're doing that right now through these 20 lines. But this code is essentially
very similar to what we saw when we were using the Mongo shell.
Now I want to show you how you would do that with Mongoose because it's a little bit different from
what we've done so far.
The first thing we have to do is to create a new schema.
And this is basically a blueprint or the structure of our data that we're going to save into our Mongo
DB database. In order to do this we can create a new const that's called fruitsSchema.
And this is going to be equal to a new mongoose schema.
And then we open up a set of parentheses and inside that we add a new Javascript object,
so we open up our curly braces.
Now in this schema, we basically scaffold out how we want data in a particular collection to be structured.
So for example if we were creating a new fruit document, what would the structure of that data look
like?
Well it might have a name which is going to be of data type string, and then it might have maybe a rating
which will be a number, and then it might have just a review which will be a text review for that fruit.
This is what our fruit schema would look like using Mongoose
and this lays out the foundation for every new fruit document that will be added to our database. After
we create the schema,
we use the schema to create a Mongoose model. And we do that by saying const Fruit = mongoose
.model.
And then we specify two parameters.
The first one is, what is going to be the name of the collection that is going to comply with this particular
schema.
Well in our case we want to create a collection of fruits right?
So we'll have these fruits each as individual records or documents, they'll be saved into a collection
called fruits and then that will be inside our database called fruitsDB.
So the first parameter is always going to be a string here.
Now the Mongoose way of doing things is to specify the singular name of your collection.
So if you have a collection of fruits then inside here will be the word "Fruit" in a singular form. And
Mongoose will very cleverly convert this string into a pluralize form to create your collection.
By doing this you will have created a new collection called fruits and those fruits have to stick to
the structure that we've specified in the fruit schema.
And now and only now are we ready to create a new fruit document.
I'm going to create something called "fruit" with a lowercase f.
This is going to be a new Fruit with a capital F and this is to show that I'm creating this document
from this model that we specified up here which means that it's going to have to stick to this schema
that we laid out here as well.
So now this new fruit is going to have a name, let's call it Apple.
It's going to be an apple that we're going to save into our database. And then we're going to give it
a rating.
And I'm going to give a rating out of 10.
So I think Apples are decent, let's give it a 7 and then
let's give it a review
"Pretty solid" as fruit. Can't really hate on apples right?
And now that we've constructed our new document, all we have to do is say fruit.save.
And this calls the save method in Mongoose to save this fruit document into a fruit collection inside
our fruitsDB. And that replaces our insertDocuments method from the Mongo client.
So at the moment you can see that we don't have our prompt. And whenever you are in that position the
first thing that will save is CONTROL + C.
This should exit out of any process that the terminal or hyper is currently performing.
And in our case, it was because we still had an active connection to our MongoDB server.
Now let's run our app.js again to save that new fruit into our database.
And if I switch over to our shell then we can go ahead and say "show dbs" to show that we've now updated
our database with a new fruitsDB and let's say use fruitsDB and now let's see what collections
we have in this database.
So we'll say "show collections". And you can see that automatically Mongo has dropped the capsule on the
earth and pluralized this fruit that we specified here into a collection of fruits.
And it's pretty clever how it does that. Behind the scenes is actually using Lodash to achieve it.
We saw that in an earlier module. But essentially it allows you to specify the singular form and work
with the singular form.
But behind the scenes it will create that collection of fruits for you to be able to work with.
So if we say "db.fruits.find" so we show everything that's inside our fruits collection,
then you can see we have a single document that has an id, a name, a rating and a review.
Now, remember that every single time you run fruit.save it will save the same fruit into your fruits
collection in your fruits database.
So if you don't want that to happen, then you can just comment out this method call and you won't end
up with a whole bunch of apples in your database.
But it's now time for a challenge.
I want you to create a new collection and this is going to be a collection of people. You need to create
the schema for a new person and they need to have two fields: a name and an age.
And then you're going to create a new model from that schema of a person and you're going to create a new
person who's called John and he's 37. And then you're going to say that new person to our database and
show it using the Mongo shell. Pause the video now and complete this challenge.
All right.
So right below our fruit.save
we're going to use the same setup but we're going to apply it to a collection of people now.
So we're still connected to the same fruits database which is exactly what we want, but we're going
to create a new person schema.
And this is going to be a new Mongoose schema and it's going to specify that every person we create
has to have a name.
And they also probably should have an age.
So the name is going to be of data type string
and the age will be data type number. And then we're going to create our model of a person from this
schema.
So it's going to equal mongoose.model and then the singular form of a person is person. But behind
the scenes we will get a collection called people that will be created. And these people inside the collection
will follow the person schema.
Using that schema we're going to create a new person and this new person is going to have a couple of
values.
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
we can save it to our database.
So now if we go back to our terminal and we exit our previous database connection and we run on node
app.js again, we can go to our Mongo shell and confirm that if we say "show collections" we now have
a collection of fruits and a collection of people.
And as I said it's pretty clever about converting your singular form into a pluralized collection.
Now if we say "db.people.find" then we end up showing all the documents that we have inside our
people collection which, is John who's 37.
What if we wanted to add a bunch of fruits in bulk like we did previously using the native MongoDB
driver?
Well let's say that we create some new fruits. Let's say const we create a kiwi. And this is going to
be a new Fruit with a capital F and the kiwi is of course called kiwi.
It has a score of "10" because kiwis are awesome and has a review of "The best fruit". And then I'm just
going to go in and add two more fruits, orange and banana. Oranges too sour for me and bananas have a
really weird texture.
So those are three fruits.
And now in order to save it in bulk, we can tap into our fruit model and we can say "insertMany".
Now how did I know that I could use fruit.
insertMany?
Well the documentation of course.
So if you head over to Mongoose and click on "Read the docs" then inside the API section you can see that they've
got all of the methods that you can do with the model listed in here.
And very often when you're working with a new package you'll be reading through the documentation and
digging through it to see what it can do.
So here we have this method called Model.insertMany and it allows us to insert an array of documents
into a particular model or basically our collection.
The syntax basically looks like this.
You specify the name of your Mongoose model which will allow it to connect to the relevant collection
and also know what the schema is
it should work with.
And then we use that method
insertMany and it takes two parameters.
The first one is an array of objects that match that particular schema,
so all fruits here. We've got kiwi, orange and bananas.
So we'll add that kiwi, orange and banana. And then the second parameter will be a callback and it allows
us to log any errors if there were any issues with inserting all of these objects into our fruits collection.
And so we can check say if there's an error then we'll log the error, but else then we'll log "Successfully
saved all the fruits to fruitsDB". And let's close that off and let's hit save and exit out of our database
and run our app.js again.
You can see that we've got that callback, "Successfully saved all of the fruits to the fruitsDB".
So there were no errors
and if we go and check our db.fruits.find, then
we now have a few more fruits.
We've got apple, kiwi, orange and banana.
We've now seen how you can create new documents and new collections using Mongoose and MongoDB. But how
exactly do we access these items in our database through our app.js?
How do we get access to living objects that our app can tap into?
Well that's what we're going to look at in the next lesson.
Can't find what you're looking for?
Get subtitles in any language from opensubtitles.com, and translate them here.