This model handles the interaction of our application with blog posts in the database. We will keep things very simple, so it will only have the following fields mentioned:
- title: This is the title of the post. It is a string value. It should not be empty, which means it is a required field.
- content: This is the body or content of the blog post. It should be a string value.
- image: This is a link to the featured image for the post. It should also be a string value.
- author: This the user who created the post. It is a reference to the ObjectId of the user who created this post on the user collection.
- createdAt: The date the document was created. This can be saved as a JavaScript date object. The default value is the current date.
- updatedAt: The date the document was most recently updated. This can be saved as a JavaScript date object. The default value is the current date.
To create the post model, let's create a Post.js file in the ./models folder, and insert the following code into it:
const mongoose = require('mongoose');
const schema = new mongoose.Schema({
title: {
type: String,
required: true
},
content: String,
image: String,
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
module.exports = mongoose.model('Post', schema);
As usual, after our schema definition, we export the model to be used elsewhere in our application.