- [Instructor] As we learned before Mongoose relies
on schemas and models.
And in this video,
we will create a schema and a model for storing items.
So as we see on this form, our item is represented by an SKU
which is an item number, and name and the price.
So let's head over to Visual Studio code and implement that.
For that to go into models,
so this directory exists already.
In there, I click on item.js.
As you see, this file is still empty
and we will now start implementing the schema.
So I start with adding Mongoose,
const mongoose = require('mongoose')
and then I start defining the schema.
Const ItemSchema = mongoose.Schema.
And in there we add now a configuration object
with our schema definition.
First we define the SKU.
And the SKU as the type, and the type should be a number.
So it should be numeric.
It should be required, so at required true
And I want it to be indexed.
So there should be a database index created in MongoDB.
And this index, and for that, I add a sub property,
a sub object.
This index should be unique, so I add unique true.
Because an SKU in any system
should be always unique of course.
And item number is always a unique identifier of an item.
Next, we have a name, that should be of type string.
So these types of all support by MongoDB.
It should be also required,
we always want the name to be present, true
and we won't set an index on the name.
Next, we have a price
and the price is again a number.
And it should be required.
Any item needs price,
and again, it should not be indexed.
A second argument,
now, you see this configuration object
was the first argument to Mongo schema.
The second argument I cannot add options.
And I want to add one option,
and this option is timestamps true.
This will make Mongoose
create two additional fields automatically.
One field will hold the timestamp
for when this document was created.
And the other field will hold the timestamp
for when the document was last updated.
And then I also have to export something from this module.
So I now add module that exports.
And I want to export a model,
so add mongoose.model.
And its first argument I know add the model name
and it should be item.
And it should use the ItemSchema that we just defined.
One thing worth noting is
that Mongoose maintains a global connection object for us.
So if we require this model,
it will use the database connection that we set up before.
This means that we don't have
to pass around the connection object within our application.
Now that we have a model,
we can start implementing our Item Management System.