After this lesson you will be able to:
In the previous learning unit, we created a Cat
model like this:
Dans notre exemple précédent, nous définission le modèle de chat suivant :
Le 2e paramètre est ce que l'on appelle le schéma. Il nous permet de donner de la structure à nos documents et évite :
The second argument that we pass is the object that will have all the fields that the documents built based on our Cat
model will have. This example is a simple version of a Schema.
In short, a schema gives our database structure. It helps us ensure consistency in our database, and we are less likely to:
number
inside a date
field or a boolean
in a number
field).Let’s take a look at how to define a Schema by adding some fields to our Cat model. Let's create folder models
and add a file Cat.js
inside models
folder. Let's add this code snippet into it:
Afin de créer des schémas plus avancés, nous allons avoir recours à la class mongoose.Schema
:
Notice how we specify our Schema, and then pass it in as the second argument to mongoose.model
. We will see this in more depth later on.
To have Cat
model available in some other file (part of the app), you need to navigate to this file from the place where you are currently. Example:
Les différents types possibles :
Our schema is just an object with keys for each of the fields’ names and values for each fields’ types. There are many schema types available in Mongoose, but here’s a quick list of common types:
String
(ex: Ironhack
)Number
(ex: 42
)Date
(ex: Date('2020-12-25')
)Boolean
(ex: true
)Schema.Types.ObjectId
: to store ids of other collections (ex: Ironhack
) - this one we will use a lot, so keep it in your mindSchema.Types.Mixed
: to store anythingArray
or []
: to store an array of anything (ex: ['foo', 42]
)
[String]
: to store an array of strings (ex: ['foo', 'bar']
)[Number]
: to store an array of numbers (ex: [42, -6]
)On peut également renseigner une valeur par défaut :
Often we want a default value for some field otherwise, it will be saved empty. For instance, when a user registers on a website and doesn't provide an image, you can set the image to some default one so the user will get the default avatar image. You can accomplish this using the keyword default
.
Notez que la valeur est maintenant un objet !
Les schémas nous permettent de faire de la validation :
Besides specifying the type of the fields or its default value, we can set more detailed validation by defining more properties:
Field property | Possible values | Description |
---|---|---|
type |
String , Number , … |
Sets a type for the field |
default |
Anything | Sets a default value |
required |
true |
Adds a required validator |
unique |
true |
Declares an unique index |
enum |
An array | Adds an enum validator |
min |
A number | Sets a minimum number validator |
max |
A number | Sets a maximum number validator |
minlength |
A number | Sets a minimum length validator |
maxlength |
A number | Sets a maximum length validator |
trim |
true |
Adds a trim setter |
lowercase |
true |
Adds an lowercase setter |
match |
A regex | Sets a regex validator |
validate |
An object | Adds a custom validator (see next part) |
set |
A function | Adds a custom setter (see next part) |
Example
Un ex concret :
If you don't have the right validator, Mongoose gives you the opportunity to write your own. For that, you will need to add validate
and precise a validator
function and an error message
.
Et même nos propres validateurs :
Mongoose also gives you the opportunity to write your setter. Every time you will set a field, Mongoose will transform the value by the function specified by set
.
Comme new
+ save()
First, let's see how we can insert (create) some documents. If you take a look at the Mongoose documentation, you will see that you can use the function Model.create()
.
Let's see how that looks if we want to create a new user based on the already defined User
model. For this demo, we'll create User.js
inside models
folder:
In the following example, we use the User
model to create a new document:
If you want to save several documents in your database, you can either use create
or insertMany
with an array as a first parameter.
Avantage : insertMany
Les paramètres de .find()
:
To retrieve multiple documents from a database, we can use Model.find()
and these are some of the specifics of its syntax:
At this point, for us the most important ones are the first and the last.
In the case we want to retrieve only one specific document, we can either use findOne
or findById
.
To update a field, you can either use updateMany
, updateOne
or findByIdAndUpdate
. In each case, you need to define first the condition (a query or an id) and then the update, like in the next example. We decided here to only use the Promise syntax.
To delete a document, you can either use deleteMany
, deleteOne
or findByIdAndRemove
, like in the next example.
Mongoose gives also some utils methods. The one you will probably use the most is the countDocuments
method, which lets you count the number of documents that match a specific condition.
Mongoose gives another way of manipulating data using the documents. We can use this approach with:
Model.find()
in its all forms (.findOne()
, .findById()
).On these documents, we can use the method .save()
to save a document in the database. We can use .save()
for creating a new document and updating one.
Cheatsheet
Model method | Description |
---|---|
create |
Create document |
insertMany |
Create many documents |
find |
Finds documents |
findOne |
Finds one document |
findById |
Finds a single document by its _id field |
updateOne |
Updates one document |
updateMany |
Updates many documents |
findByIdAndUpdate |
Updates a single document based on its _id field |
deleteOne |
Deletes one document |
deleteMany |
Deletes many documents |
findByIdAndRemove
| Removes a single document based on its _id
field
countDocuments
| Counts number of matching documents in a database collection
Document method | Description |
---|---|
save |
Saves this document |
toObject |
Converts this document into a plain javascript object |
toString |
Helper for console.log |
In this lesson, we learned how to build more complex schemas, with different types, validators and setters.
We have also seen Mongoose methods to perform all sorts of operation in the database and to discover new interesting things about them you can take a look into the Mongoose API documentation.