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
根据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包。
| 归档时间: |
|
| 查看次数: |
9925 次 |
| 最近记录: |