首页 > 解决方案 > 每次创建文章并将其保存在数据库中时,如何生成 slug?

问题描述

所以,我有这篇文章架构,我想在其中创建一个独特的 slug。

const mongoose = require("mongoose")
const Schema = mongoose.Schema
var URLSlug = require('mongoose-slug-generator')

const articleSchema = new Schema({
    title: { type: String, required: true },
    description: { type: String, required: true },
    userId: { type: Schema.Types.ObjectId, ref: "User" },
    slug: { type: "String", slug: "title", unique: true }
}, { timestamps: true })


articleSchema.pre("save", function(next) {
    this.slug = this.title.split(" ").join("-")
    next()
})

articleSchema.plugin(URLSlug("title", {field: "Slug"}))

const Article = mongoose.model("Article", articleSchema)

module.exports = Article

这是文章控制器

    newArticle: (req, res) => {
        Article.create(req.body, (err, newArticle) => {
            if (err) {
                return res.status(404).json({ error: "No article found" })
            } else {
                return res.status(200).json({ article: newArticle })
            }
        })
    }

我不知道,当我在邮递员中检查时,它说没有找到文章,更不用说蛞蝓了!另外,我收到此错误:

schema.eachPath is not a function

标签: node.jsmongodbexpressmongooseslug

解决方案


根据mongoose-slug-generator您需要在 mongoose 上应用插件,但在您的代码中它被应用到模式。

因此,如果您尝试使用此代码,它将起作用:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
var URLSlug = require("mongoose-slug-generator");

mongoose.plugin(URLSlug);

const articleSchema = new Schema(
  {
    title: { type: String, required: true },
    description: { type: String, required: true },
    userId: { type: Schema.Types.ObjectId, ref: "User" },
    slug: { type: String, slug: "title"}
  },
  { timestamps: true }
);

articleSchema.pre("save", function(next) {
  this.slug = this.title.split(" ").join("-");
  next();
});

const Article = mongoose.model("Article", articleSchema);

module.exports = Article;

如果我们像这样发送 req.body :

{
    "title": "metal head dev",
    "userId": "5e20954dc6e29d1b182761c9",
    "description": "description"
}

保存的文档将是这样的(如您所见 slug 已正确生成):

{
    "_id": "5e23378672f10f0dc01cae39",
    "title": "metal head dev",
    "description": "description",
    "createdAt": "2020-01-18T16:51:18.445Z",
    "updatedAt": "2020-01-18T16:51:18.445Z",
    "slug": "metal-head-dev",
    "__v": 0
}

顺便说一句mongoose-slug-generator,似乎很老了,有一个更流行且维护良好的slugify包。


推荐阅读