MVC, Node, and Express: The Model (Part 3)

Welcome to Part 3 of implementing MVC architecture in Node and Express. In this part, we’ll be discussing how to connect the controller to the database, which is represented by the Model in MVC.

To recap, the model is responsible for storing and responding to requests for data.

—-

In the main app.js file, we can connect to our database using the following code:

const express = require('express')
const mongoose = require('mongoose')

const app = express();
const port = 3000;

app.use('/', require('./routes/index'))

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

mongoose.connect(`mongodb+srv://${MONGODB_USERNAME}:${MONGODB_PASSWORD}@cluster0.pdykdce.mongodb.net/${MONGODB_DATABASE_NAME}?retryWrites=true&w=majority`)
    .then(() => console.log('MongoDB Connected'))
    .catch(err => console.log(err))

Notice that there are two new lines of code here. The first

const mongoose = require('mongoose')

imports the mongoose package and the second line

mongoose.connect(`mongodb+srv://${MONGODB_USERNAME}:${MONGODB_PASSWORD}@cluster0.pdykdce.mongodb.net/${MONGODB_DATABASE_NAME}?retryWrites=true&w=majority`)
    .then(() => console.log('MongoDB Connected'))
    .catch(err => console.log(err))

is a connection string provided by MongoDB. This makes an asynchronous call to connect to the database. When fulfilled, there is a success statement logged to the console.

Once again, this database connection statement could be moved to a separate file using require( ) and module.export( ) statements.

The Schema

One of the most important features of the Model is providing a template for how data should be received and stored in the database. This is often referred to as input validation on the front end and data validation on the back end.

Within the Mongoose framework, one way to structure data is through the schema. A sample schema is provided below:

const mongoose = require('mongoose')

const UserSchema = new mongoose.Schema({
    displayName: {
        type: String,
        required: true
    },
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true
    },
    image: {
        type: String,
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
})

module.exports = mongoose.model('User', UserSchema)

When a new user profile is created on the website, these six attributes will be associated with each user. By creating this Schema, the database will always receive data in an expected format (Display Name, First Name, Last Name, Profile Picture, and date created). The final line of code exports this Schema as a module to be used in other parts of the project.

Writing to the Database

As seen before, this module can then be imported and used elsewhere in the project using the following statement:

const User = require('../models/User')

The following lines of code create a user following the standards of the Schema and then save it to the database:

const newUser = {
            googleId: 39f39j2r9f39jA9f3jnvbsY,
            displayName: AwesomeUser,
            firstName: Bob,
            lastName: Coder,
            image: sampleimage.png
        }

User.create(newUser)

Reading from the Database

Pulling data from the database is similarly straightforward. If we wanted to find a user’s profile and then sign them in, we could use the following line of code:

User.findOne({ googleId: 39f39j2r9f39jA9f3jnvbsY })

Of course, in an actual project, these values would not be hard coded and would instead be dynamically accessed. The code for authentication is omitted for brevity.

And that’s it for the Model, the second layer in MVC! Continue to Part 4 where we talk about the final layer, the View.

Previous
Previous

MVC, Node, and Express: The View (Part 4)

Next
Next

MVC, Node, and Express: The Controller (Part 2)