slugify in model

This commit is contained in:
2018-05-17 13:11:57 +03:00
parent 1317015a0d
commit 325d01e945
4 changed files with 19 additions and 7 deletions

View File

@@ -9,6 +9,7 @@
}
],
"no-console": "off",
"no-underscore-dangle": ["warn", { "allow": ["_id"] }]
"no-underscore-dangle": ["warn", { "allow": ["_id"] }],
"func-names": "off"
}
}

View File

@@ -2,7 +2,7 @@ const mongoose = require('mongoose');
const { Schema } = mongoose;
const todoSchema = Schema({
const TodoSchema = Schema({
text: {
type: String,
required: true,
@@ -11,4 +11,4 @@ const todoSchema = Schema({
completed: { type: Boolean, default: false },
});
mongoose.model('Todo', todoSchema);
mongoose.model('Todo', TodoSchema);

View File

@@ -1,11 +1,13 @@
const mongoose = require('mongoose');
const slugify = require('slugify');
const { Schema } = mongoose;
const todoListSchema = Schema({
const TodoListSchema = Schema({
name: {
type: String,
required: true,
lowercase: true,
},
slug: {
type: String,
@@ -14,4 +16,15 @@ const todoListSchema = Schema({
todos: [{ type: Schema.Types.ObjectId, ref: 'Todo' }],
});
mongoose.model('TodoList', todoListSchema);
TodoListSchema.pre('validate', function (next) {
if (!this.slug) {
this.slugify();
}
next();
});
TodoListSchema.methods.slugify = function () {
this.slug = slugify(this.name);
};
mongoose.model('TodoList', TodoListSchema);

View File

@@ -1,6 +1,5 @@
const express = require('express');
const mongoose = require('mongoose');
const slugify = require('slugify');
const router = express.Router();
@@ -27,7 +26,6 @@ router.post(
asyncHelper(async (req, res) => {
const { name } = req.body;
const newList = new TodoList({ name });
newList.slug = slugify(name);
await newList.save();
res.json({ success: true });
}),