Tutorial: Getting Started 4: Database & ORM

Getting Started 4: Database & ORM

Flitter uses Mongoose to provide MongoDB models. Model schemas are defined in files and loaded into Mongoose when Flitter initializes. MongoDB connection info is specified in the environment configuration.

Defining Model Schemata

Side Note:
schemata (n. pl.) - plural of schema

Model schemata define the structure and fields of the model. The schemata are passed directly to Mongoose, so for the most part, you can just reference the Mongoose docs for how to create a schema. The schemata should be defined in individual files in the app/models/ directory. Each of these files should return the object-definition of the Mongoose schema. Here's an example:

// models/auth/User.js
const User = {
    username: String,
    password: String,
    uuid: String,

module.exports = User

Custom model definitions can be created and added to the app/models/ directory. You can use the ./flitter command to generate the model with any given name. Model names are parsed from the file name and follow the standard Flitter convention for sub-directory naming. For example:

./flitter new model subdirectory:file_name

This will generate the file app/models/subdirectory/file_name.model.js, which can be referenced as subdirectory:file_name:

 * file_name Model
 * -------------------------------------------------------------
 * Put some description here!
const file_name = {
    field_name: String,

module.exports = exports = file_name

Using Models

When Flitter starts, it loads each of the schemata and creates Mongoose models. These models are made available globally via the _flitter.model() function. Flitter model names are parsed from the file name and follow the standard Flitter convention for sub-directory naming. Interacting with these models is simply interacting with normal Mongoose models, for which you can refer to the excellent Mongoose docs. Here's an example of using the global function to use a model:

// excerpt from app/controllers/Auth.controller.js
login_post( req, res ){
    // Get the User model.
        const User = _flitter.model('auth:User')

        // Interact with it as you normally would.
        User.findOne({username: req.body.username}, (err, user) => {
            if ( !user ){
                create_error_session('username', 'Invalid username.')
                return res.redirect('/auth/login')

            bcrypt.compare( req.body.password, user.password, (err, match) => {

                if ( !match ){
                    create_error_session('password', 'Invalid password.')
                    return res.redirect('/auth/login')
                else {

                    _flitter.controller('Auth').create_auth_session(req, user)

                    return res.redirect('/auth/dash')

Next: 5: Controllers