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.
Part of Databases
- Introducing databases
- Organising a databaseP
- Using a database driverP
- Creating modelsP
- Making forms workP
- Collecting form dataP
- Saving form dataP