Closed darkestblue91 closed 7 years ago
Hi @darkestblue91, check the PR #26 I sent out. I added the 'recreate' option that will basically re-create the slug each time. update
only updates the slug if the fields have changed.
Hey Peter,
Im having problems to make this work, this mongoose operation works with this option?
Tour.findByIdAndUpdate(req.params.id, req.body, {new: true}, (err, tour) => {}
Or I have to use another.
Thanks.
@darkestblue91 I have the similar problem like you. From test results, I think Mongoose's findByIdAndUpdate()
doesn't work with this plugin right now. You have to use findById()
and save()
. Like
router.patch('/:id', function (req, res, next) {
Group.findById(req.params.id, function (err, group) {
if (err) return res.status(404).send('not found');
group.name = req.body.name;
group.save(function (err, group) {
res.json(group);
});
});
});
Maybe Mongoose's findByIdAndUpdate()
and update()
functions are not calling this plugin before they write data to MongoDB.
Found the official answer from Mongoose:
By design. There are no docs to call hooks on. Model.update, findByIdAndUpdate, findOneAndUpdate, findOneAndRemove, findByIdAndRemove are all commands executed directly in the database.
https://github.com/Automattic/mongoose/issues/964#issuecomment-6367106
This means, when you call these methods, slug will not get updated. They should only be used to modify data that do not require middlewares / plugins. So always use save()
instead of update()
if you want your slug to be updated.
@guoyunhe That is correct. I knew this when I wrote this plugin, just forgot to mention it on the Readme. I am going to keep in mind to add this little info to it.
There are numerous options available in the latest release that should be able to resolve the issue you are facing. Closing this, if you still feel there is an issue, feel free to submit another issue.
No, thanks for all the info, it works!
I can make the plugin modify the slug when Mongoose update, is that posible?
I read the documentation and set update field to true but it wont work :(
Using this code:
type.plugin(slug('name', { field: 'slug', update: true }));