mongoose-url-slugs icon indicating copy to clipboard operation
mongoose-url-slugs copied to clipboard

Not Found using method findByIdAndUpdate

Open carlosalbertocruz opened this issue 6 years ago • 2 comments

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

carlosalbertocruz avatar Aug 19 '19 12:08 carlosalbertocruz

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!

gideonibemerejr avatar Sep 07 '19 23:09 gideonibemerejr

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

frontshift avatar Jan 26 '22 12:01 frontshift