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

Duplicate slug generated when subdocument added to existing document #25

Closed mykwillis closed 3 years ago

mykwillis commented 3 years ago

I have a document that has an array of subdocuments. Each subdocument contains a permanent slug unique to the parent:

const ChildSchema = mongoose.Schema({
  title: {
    type: String
  },
  slug: {
    type: String,
    slug: 'title',
    index: true,
    permanent: true,
    slugPaddingSize: 4,
    uniqueGroupSlug: '/_id',
  },
});

const ParentSchema = mongoose.Schema({
  children: [ChildSchema],
});

const ExampleModel = mongoose.model('ParentSchema', ParentSchema);

If I create an initial document with some children:

    const doc = await ExampleModel.create({
      children: [
        {
          title: 'This is nested subtitle',
        },
        {
          title: 'This is nested subtitle',
        },
      ],
    });

then everything is fine; both of the new subdocuments get properly generated and unique slugs.

However, if I update the document with another child subdocument:

    doc.children.push(
    {
      title: 'This is nested subtitle',
    });
    await doc.save()

then the new document receives a duplicate slug.

YuriGor commented 3 years ago

Thank you for report and PR! Sorry for late reaction, something went wrong with notifications about this project.