YuriGor / mongoose-slug-updater

Schema-based slug plugin for Mongoose - single/compound - unique over collection/group - nested docs/arrays - relative/abs paths - sync on change: create/save/update/updateOne/updateMany/findOneAndUpdate tracked - $set operator - counter/shortId
MIT License
40 stars 13 forks source link

Is there possibility to add incremental counter without setting slugPaddingSize? #24

Closed patrykgulas closed 2 years ago

patrykgulas commented 4 years ago

I'm thinking about use case where I would like to create unique slugs with incremental counter but without setting slugPaddingSize. At this moment when I set slugPaddingSize to 1 I see that behaviour:

title
title-1
title-2
title-3
title-4
title-5
title-6
title-7
title-8
title-9
title-10
title-10
...

And I would like to see something like this:

title
title-1
title-2
title-3
title-4
title-5
title-6
title-7
title-8
title-9
title-10
title-11
...

Is it possible to do that with this plugin?

YuriGor commented 4 years ago

Hi, it should work as you expect with pad 1, it looks like a bug. I will take a look.

patrykgulas commented 4 years ago

Thanks for reply. I just made another test with same result. Here is my simplified configuration:

import mongoose, { Schema } from 'mongoose'
import slug from 'mongoose-slug-updater'

mongoose.plugin(slug)

const postSchema = new Schema({
    title: {
      type: String,
      required: true,
      maxlength: 64,
      minlength: 1
    },
    slug: { type: String, slug: 'title', slugPaddingSize: 1, unique: true }
},
{
  timestamps: true,
    toJSON: {
      virtuals: true,
      transform: (obj, ret) => {
        delete ret._id
      }
    }
})
YuriGor commented 4 years ago

Ok, I checked this, and it's more not a bug but like an unexpected limitation (so I need to document it) Internally, to decide which counter to use, plugin queries similar docs sorted by given slug field in a descending order, assuming it will get the biggest counter that already exists in the collection. But this works only for the correct number of padded zero characters, because slug filed is a string field, so sorting is performed alphabetically. when we sort string alphabetically xxx-9 is greater thaen xxx-10, because character '9' goes after character '1'.

So sorry, counter will work only within given padding interval. after that it will start failing (so I probably need to throw an exception if max counter exceeded).

No plans for improving this. Only way I see is to improve this - to have extra counter field additionally to each counter slug. Or extra collection for counters - that's sounds even worse.

If you have better idea how to implement this without extra fields/collections - welcome to discuss