W
W
wufapexef2018-03-26 16:43:45
MongoDB
wufapexef, 2018-03-26 16:43:45

Why doesn't the pre-save hook work when I update the data?

There is a hook that creates a slug from a title

articleSchema.pre('save', async function(next) {
  if(!this.isModified('title')) {
    next()
    return
  }
  this.slug = slug(this.title)
  const slugRegEx = new RegExp(`^(${this.slug})((-[0-9]*$)?)$`, 'i')
  const articlesWithSlug = await this.constructor.find({slug: slugRegEx})
  if(articlesWithSlug.length) {
    this.slug = `${this.slug}-${articlesWithSlug.length + 1}`
  }
  next()
})

Everything works as expected on initial save, but if I change the title, the slug doesn't change. Why? How to fix?
UPD:
I found that you can use the hook on findOneAndUpdate(I use it for updating). But still doesn't work. Problem with this.isModified. Apparently, the for hook findOneAndUpdatereturns different data than the save. Damn with this Monguz more problems than help! Understand these wilds of API, undocumented, constantly changing. Shit is over!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question