title - String
author - String
body - String
status - Enumerator ("PENDING", "PUBLISHED")
view_count - Number
created_at - Date
Before writing Mongoose schema, make sure you have installed package by:npm install mongoose --save
Let's go straightforward and write our schema.
/models/Post.js
const mongoose = require('mongoose');
var PostSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
author: {
type: String,
required: true
},
body: {
type: String,
default: ''
},
status: {
type: String,
enum: ["pending", "published"]
default: "pending"
},
view_count: {
type: Number,
default: 0
},
created_at: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Post', PostSchema);
It is a very simple schema for now. But we can add complex nested schemas, pre-save method, build-in validations, and so on.
Let add a category of the blog in schema. But we will add category schema as parent and blogs will be children of category.
const mongoose = require('mongoose');
var PostSchema = new mongoose.Schema({
...
});
var CategorySchema = new mongoose.Schema({
title: {
type: String,
required: true
},
posts: [ PostSchema ],
created_at: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Category', CategorySchema);
As you can see, now we have one document of category, and posts will be placed as an array of objects of a category. You can up to 100 nested levels which limited by MongoDB.
Mongoose also provides other facilities, such as querying, populating data, validation. For more info visit Mongoose documentation.
If you interested in CRUD operation using Mongoose and Node JS, please visit this post.
If you have any question regarding Mongoose, you can reach via mr.nodirbek77@gmail.com.
Comments
Post a Comment