Node.js 如何在每次创建文章并将其保存在数据库中时生成slug?
因此,我有一个articleSchema,我想在其中创建一个唯一的slugNode.js 如何在每次创建文章并将其保存在数据库中时生成slug?,node.js,mongodb,express,mongoose,slug,Node.js,Mongodb,Express,Mongoose,Slug,因此,我有一个articleSchema,我想在其中创建一个唯一的slug const mongoose = require("mongoose") const Schema = mongoose.Schema var URLSlug = require('mongoose-slug-generator') const articleSchema = new Schema({ title: { type: String, required: true }, descriptio
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
这是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不是一个函数
根据您需要在mongoose上应用插件,但在您的代码中,它应用于架构
因此,如果您尝试使用此代码,它将起作用:
const mongoose=require(“mongoose”);
const Schema=mongoose.Schema;
var urlslaug=require(“mongoose段塞发生器”);
插件(URLSlug);
const articleSchema=新模式(
{
标题:{type:String,必需:true},
描述:{type:String,必需:true},
userId:{type:Schema.Types.ObjectId,ref:“User”},
slug:{type:String,slug:“title”}
},
{时间戳:true}
);
articleSchema.pre(“保存”,函数(下一步){
this.slug=this.title.split(“”).join(“”);
next();
});
const Article=mongoose.model(“Article”,articleSchema);
module.exports=物品;
如果我们发送如下所示的req.body:
{
"title": "metal head dev",
"userId": "5e20954dc6e29d1b182761c9",
"description": "description"
}
保存的文档如下所示(如您所见,slug已正确生成):
顺便问一下,
mongoose slug generator
似乎很旧,有一个更受欢迎且维护良好的软件包。Hi,你检查了我的答案了吗?不客气,你能把我的答案标记为答案吗?您作为请求主体发送了什么?您是否按照我的回答替换了所有架构代码?我试过这个,效果很好。你能试一下吗?删除模式中slug字段中的unique选项。删除文章集合(如果需要备份集合),然后再试一次?您能告诉我,在使用slagify
时,您将如何处理两个类似的标题吗?
{
"_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
}