产品的slug是在我发布产品时创建的。但是当我更改产品名称时,slug 没有更新。
这是我的代码:
const mongoose = require('mongoose');
const { default: slugify } = require('slugify');
const ProductSchema = new mongoose.Schema(
{
name: {
type: String,
trim: true,
unique: true,
required: [true, 'Please add product name'],
},
slug: String,
sku: {
type: String,
trim: true,
required: [true, 'Please add product sku'],
},
isActive: {
type: Boolean,
default: true,
},
createdAt: {
type: Date,
default: Date.now,
},
updatedAt: {
type: Date,
default: Date.now,
},
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
ProductSchema.pre('save', function (next) {
this.slug = slugify(this.name, { lower: true });
next();
});
module.exports = mongoose.model('Prduct', ProductSchema );
我想在更改名称时自动更新slug
您可以使用 virtuals 来实现此目的。删除架构上的属性并使用它:
ProductSchema.virtual('slug').get(function() {
return slugify(this.name, { lower: true });
});
该属性实际上并不存在于数据库中,并将根据当前名称动态确定。
使用
slugify
模块和 `mongoose.pre('save')` 中间件的另一个解决方法是:
例如
// someModel.js
const mongoose = require('mongoose');
const slug = require('slugify');
const ProductSchema = new mongoose.Schema(
{
name: {
type: String,
trim: true,
unique: true,
required: [true, 'Please add product name'],
},
slug: String,
sku: {
type: String,
trim: true,
required: [true, 'Please add product sku'],
},
isActive: {
type: Boolean,
default: true,
},
createdAt: {
type: Date,
default: Date.now,
},
updatedAt: {
type: Date,
default: Date.now,
},
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
ProductSchema.pre('save', async function (next) {
const product = this
if (!product.isModified('name')) return next()
const slug = slugify(product.name, { lower: true, trim: true })
product.slug = slug
return next()
});
module.exports = mongoose.model('Prduct', ProductSchema );
// someController.js
const updateProduct = async (req, res) => {
const { productId } = req.params
const { name, ... } = req.body
// const product = await Product.findOneAndUpdate(filter, update, { new: true }) not working instead:
let product = await Product.findById(productId)
product?.name = name
...
await product.save()
return product
}
编码快乐!