talha-asad / mongoose-url-slugs

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

Not Found using method findByIdAndUpdate #48

Open carlosalbertocruz opened 5 years ago

carlosalbertocruz commented 5 years ago

Not update after send PUT using method findByIdAndUpdate, Object 'slug' not updated.

gideonibemerejr commented 5 years ago

This issue could be because the findByIdAndUpdate() method is filtering through and looking to return an object where

{_id: "<yourSlugValue>"}

I do not believe this is the result you are looking for, but correct me if I'm wrong.

You would have to use the findOneAndUpdate() method to handle your PUT request instead.

Inferring based on the issue you seem to have presented, you can do the following instead.

The code example below is a Blog post with a slug we want to update.

const BlogPost = mongoose.model('BlogPost', new mongoose.Schema({
  title: String,
  slug: String
}));

// NOTE: I skipped the slug creation, as that is what mongoose-url-slugs is for. 
await BlogPost.create({ title: 'Slug City', slug: 'slug-city' });

// here we define the filter and update that the findOneAndUpdate method requires. You can define these inline as well, but this is a bit more tidy.
const filter = {title: 'Slug City' };
const update = { slug: 'slug-city-2' };

// `post` is the document _before_ `update` was applied

let post = await BlogPost.findOneAndUpdate(filter, update);
post.title; // will return 'Slug City'
post.slug; // will return 'slug-city'

// however, upon searching for the document again, the `update` is applied
post = await BlogPost.findOne(filter);
post.slug ; // will return 'slug-city-2'

Hope this helps!

frontshift commented 2 years ago

having the same issue with findOneAndUpdate() The slug does not get updated when the fields that make up the slug change, e.g.

schema.plugin(URLSlugs('firstName lastName'));

await this.managerModel.findOneAndUpdate({ userId: id }, { firstName: 'new first name', lastName: 'new last name');

Just saw an issue saying that findOneAndUpdate among others are applied directly in the database, so they don't work with middleware. However I am facing the same issue when I just get the entry and call model.save() after updating the fields