dsanel / mongoose-delete

Mongoose Soft Delete Plugin
MIT License
346 stars 101 forks source link

save method can reset the deleted flag #140

Closed batyshkaLenin closed 9 months ago

batyshkaLenin commented 1 year ago

If you don't take the deleted field in select, the deleted field will be reset when you use save later.

For example:

const user = await DB.User.findOne({ email: 'mail@mail.com' }).select('_id firstname');

user.firstname = 'new name';

await user.save();

This code works valid and not reset deleted field:

const user = await DB.User.findOne({ email: 'mail@mail.com' }).select('_id firstname deleted');

user.firstname = 'new name';

await user.save();
dsanel commented 9 months ago

Hi @batyshkaLenin, the mongoose-delete is a simple plugin that will try to do "default" { deleted: false } if we missing this value. If you do not configure specific plugin configuration and use overridden static methods, or simply select the deleted field, it will work as Mongoose defines.

For example, try to run this code without mongoose-delete plugin and see what will happen

const user = await DB.User.findOne({ email: 'mail@mail.com' }).select('-_id firstname');

user.firstname = 'new name';

await user.save();

Notice -_id in this example. So, Mongoose requires this field to work properly, and if we do not provide it, it will probably raise an error like MongooseError('No _id found on document!')...