Node.js Blog System
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

49 lines
1.0 KiB

  1. const mongoose = require("mongoose");
  2. const slugify = require("slugify");
  3. const marked = require("marked");
  4. const createDomPurify = require("dompurify");
  5. const { JSDOM } = require("jsdom");
  6. const dompurify = createDomPurify(new JSDOM().window);
  7. const articleSchema = new mongoose.Schema({
  8. title: {
  9. type: String,
  10. required: true,
  11. },
  12. description: {
  13. type: String,
  14. required: true,
  15. },
  16. markdown: {
  17. type: String,
  18. required: true,
  19. },
  20. createdAt: {
  21. type: Date,
  22. default: Date.now,
  23. },
  24. slug: {
  25. type: String,
  26. required: true,
  27. unique: true,
  28. },
  29. sanitizedHtml: {
  30. type: String,
  31. required: true,
  32. },
  33. });
  34. articleSchema.pre("validate", function (next) {
  35. if (this.title) {
  36. this.slug = slugify(this.title, { lower: true, strict: true });
  37. }
  38. if (this.markdown) {
  39. this.sanitizedHtml = dompurify.sanitize(marked(this.markdown));
  40. }
  41. next();
  42. });
  43. module.exports = mongoose.model("Article", articleSchema);