BETAThis is a new service – your feedback will help us to improve it.

Creating models

Now we've successfully connected to our database, we can use it to store data, and fetch data from it.

In order to do that, we need to create at least one model for the database.

A model is a detailed blueprint telling our app:

  • How to read all the documents in a particular collection
  • How to read, change or delete a particular document in the collection
  • How to add a new document to that collection

We need one model for every collection.

Create a new folder called /models, where your models will live.

If we were making a blogging app, we might create a file in this folder called postModel.js.

Inside, it might say:

const mongoose = require('mongoose');

const model = new mongoose.Schema({
  title: String,
  datePublished: String,
  category: Array,
  content: String,
  visible: Boolean
})

module.exports = mongoose.model('Post', model);

We start by getting the Mongoose code with require().

We define our model in the middle section, which should be familiar from earlier in this module.

The final line makes our model available for use in other files. Eventually, we will reference in server.js.

On the final line, we also name our model Post.

Using the ideas you wrote out earlier in this module, make a model for every collection in your database.
Lessons last updated 12th July 2019. You can improve this lesson on Github.
Part of Databases
  1. Introducing databases
  2. Organising a databaseP
  3. Using a database driverP
  4. Creating modelsP
  5. Making forms workP
  6. Collecting form dataP
  7. Saving form dataP