Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Not Found using method findByIdAndUpdate #48

Open
carlosalbertocruz opened this issue Aug 19, 2019 · 2 comments
Open

Not Found using method findByIdAndUpdate #48

carlosalbertocruz opened this issue Aug 19, 2019 · 2 comments

Comments

@carlosalbertocruz
Copy link

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

@gideonibemerejr
Copy link

gideonibemerejr commented Sep 7, 2019

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
Copy link

frontshift commented Jan 26, 2022

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants