node.jsmongodbmongoosemongoose-schema

How can I update slug automatic when I will be changed name with slugify mongoose?


The product's slug is created when I post a product. But the slug did not update when I changed the product name.

Here is my code:

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 );

I want to update the slug automatically when the name is changed


Solution

  • You can use virtuals for this. Delete the property on the schema and use this instead:

    ProductSchema.virtual('slug').get(function() {
      return slugify(this.name, { lower: true });
    });
    

    The property will not actually exist in the database and will be dynamically determined based on whatever the current name is.