KeystoneJS, A Javascript CMS (Part 2— Code Structure and the DB Model)

Shivendra Odean
2 min readMay 29, 2017

--

Part 1 — Getting Started
Part 2 — Code Structure & the DB Model

Part 3 — Routes, View, and Templates
Part 4 — Accessing Data

In the last session, we performed our mandatory installations and generated our app called myschool (a very simple website for a school). We will now familiarise ourselves with the code structure, and create a database model.

Code Structure

models — Contains database models. We will discuss this later in further detail.

public — Static resources publicly available to the app.

routes — Javascript files, such as view controllers and api controllers.

templates —Contains semantic view templates.

Important Files

keystone.js- The main application file which configures and starts the app.
routes/index.js- Route endpoints are registered here.
templates/views/layouts/default.hbs- This is the main template file.

Creating a Model

1. Create a new file inside the models folder called ‘Announcement.js’.

var keystone = require('keystone');
var Types = keystone.Field.Types;
var Announcement = new keystone.List('Announcement');Announcement.add({
title: { type: Types.Text, initial: true, required: true },
description: { type: Types.Textarea, initial: true, required: true
},
date: { type: Types.Datetime, default: Date.now, initial: true,
required: true }
});
Announcement.register();

The initial option above causes the field to be displayed in the Create Form of the Admin UI. The required option validates that the field has a value before an item can be saved (also passed to mongoose and enforced using a database index).

The Types module(http://keystonejs.com/docs/database/#fieldtypes) is used to define the data type of each property inside the Mongo DB document.

2. Run the app again (node keystone.js).
Then browse to http://localhost:3000/keystone/. You should see the Announcement Model added to the Admin UI.

--

--