0

I am unable to delete (in mongoose, its called unset) the field from the mongoose, but $unset is working. The following example will demonstrate my problem very well though.

Without $unset

let user = await User.findById(user_id);
delete user.last_name;
await user.save();

user = await User.findById(user_id);
console.log(user.last_name); // Santiago 

With $unset

await User.findByIdAndUpdate(user_id, { $unset: { last_name: true } });

let user = await User.findById(user_id);
console.log(user.last_name); // undefined 
tbhaxor
  • 1,659
  • 2
  • 13
  • 43

1 Answers1

3

The last_name property of the user Document instance is a getter function that Mongoose adds from the model schema to make life easier.

The real document that you might be able to delete from is held in an internal variable.

You can set a field to undefined and mongoose will work it out for you:

user.last_name = undefined
await user.save()
Matt
  • 68,711
  • 7
  • 155
  • 158