Series: Introduction to the MEAN Stack
Mongoose is a framework which is based on the native MongoDB driver and extends it with extensive modfunctions. We revisit the example from the last chapter and formulate it in such a way that we get more structure in our documents.
The basis of Mongoose are schemas , which represent an abstract description of the documents in a collection. Using schemas, fields in a document can be checked for a type, incoming data can be validated, and default values can be assigned. It is also possible to use virtual fields, which can be used by the server, but which are not to be stored in the MongoDB database. Another feature is freely definable hooks , special functions that are executed before or after an event (like saving a document). As you can see Mongoose is quite extensive. You can find the complete documentation here .
Mongoose is installed via npm. The latest version at the time of writing is 3.6.2.
1
|
$ npm install mongoose
|
Our previous example, written with Mongoose, looks like this:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
var mongoose = require ( ‘mongoose’ ) ;
mongoose. connect ( ‘mongodb: // localhost: 27017 / first-db’ ) ; var VisitSchema = new mongoose. Schema ( { url : String , time : { type : Date , default : Date. Now } } ) ; var Visit = mongoose. model ( ‘Visit’, VisitSchema ) ; var express = require ( ‘express’ ) ; |
In the third line we create a schema for our visits. We specify that documents for the visits have two fields: a field url
of type String
and a field time
of type Date
. At the same time, we set time
a default value for the field . This is automatically set when the field is empty when the document is saved. Then, the abstract schema creates a so-called model, which provides an API for storing and finding documents (similar to the collection in the previous example). The rest of the code behaves in the same way as the previous example. In the middleware, we simply do not have to save the time of the visit explicitly since our schema takes over this task.
Your result should look something like this:
As you can see, the entries from the previous example have been preserved. We finally use the same database! Only the specification of the time has been formatted differently since we have defined time
the type for the field Date
and Mongoose pre-formatted the value accordingly.
In the next article, I introduce you to the concept of REST . With REST, we can later query and manipulate the data from our database via a client – the server serves as an intermediary between the client and the database. This is a nice concept that combines all our technologies of the MEAN stack.
0 Comments