如何在每次创建文章并将其保存在数据库中时生成 slug?

met*_*Dev 1 slug mongoose mongodb node.js express

因此,我有这篇文章架构,我想在其中创建一个独特的 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
Run Code Online (Sandbox Code Playgroud)

这是文章控制器

    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 })
            }
        })
    }
Run Code Online (Sandbox Code Playgroud)

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

schema.eachPath is not a function

Sul*_*Sah 5

根据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;
Run Code Online (Sandbox Code Playgroud)

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

{
    "title": "metal head dev",
    "userId": "5e20954dc6e29d1b182761c9",
    "description": "description"
}
Run Code Online (Sandbox Code Playgroud)

保存的文档将如下所示(如您所见,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
}
Run Code Online (Sandbox Code Playgroud)

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

  • `mongoose-slug-generator` 和 `slugify` 不一样。`slugify` 仅从字符串生成 SEO 友好的 URL。而“mongoose-slug-generator”除了处理将 slug 存储在数据库中并避免重复之外,还执行相同的操作。事实上,“mongoose-slug-generator”使用了一个名为“speakingurl”的包,它与“slugify”几乎相同。 (2认同)