talha-asad / mongoose-url-slugs

Create URL compatiable slugs on mongoose models, ensuring uniqueness.
MIT License
40 stars 22 forks source link

No retroactive way to create slugs #35

Closed truca closed 7 years ago

truca commented 7 years ago

I had a populated database when i started using your package (thank you for it, it's great). It works great, but my old docs dont have a slug and i can't find a way to trigger the slug creation for them.

talha-asad commented 7 years ago

I think what you are looking for is alwaysRecreate option. You just need to ping all the docs which don't have it.

truca commented 7 years ago

I tried it (set it to true and then used find), but it didn't work. What do you mean by "ping"?

talha-asad commented 7 years ago

Fetch the document, mark the slug depending field modified using doc.markModified and then save it.

truca commented 7 years ago

Thank you very much!

truca commented 7 years ago

For future cases:

I created this function to reatroactively generate the slugs for previous documents. (you have to set the alwaysRecreate parameter to true). All my models are inside of the "Models" object and their key is the model's name

const slug = (model) => {
  Models[model.name].find({}, (err, elements) => {
    if(!err){
      elements.forEach((element) => {
        element.markModified(model.attribute)
        element.save()
      })
    }
  })
}

Example calling(name is the model, attribute is the model's attribute that defines the slug): slug({name: "country", attribute: "name"})