mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

Performance: avoid cloning when saving document if `minimize: false`

Open vkarpov15 opened this issue 2 months ago • 3 comments

Prerequisites

  • [x] I have written a descriptive issue title
  • [x] I have searched existing issues to ensure the issue has not already been raised

Issue

In $__handleSave() we have the following:

  if (this.$isNew) {
    // send entire doc
    const obj = this.toObject(saveToObjectOptions);

However, if minimize: false, we don't need to run toObject(), we can just do const obj = this._doc because the MongoDB driver will clone and apply toBSON() anyway. This should significantly help performance.

Re: #8024, let's implement this functionality first and make sure it works as intended before considering making minimize default to false.

vkarpov15 avatar Oct 20 '25 19:10 vkarpov15

We did some digging and this doesn't help as much as we originally thought. BSON serialization calls toBSON() which calls toObject() anyway. So this saves cloning the top level document props, but any arrays or subdocs still get toObject() treatment. In order to get substantial benefit we would need to store subdocs as POJOs in _doc, which is a more substantial undertaking.

Will defer this project for later

vkarpov15 avatar Nov 10 '25 20:11 vkarpov15

Hi @vkarpov15, I’m interested in contributing to this issue. I understand that it’s currently deferred, but I’d love to explore the cloning optimization when minimize: false and evaluate possible improvements around subdocument handling or BSON serialization behavior.

If you’re open to it, could I start experimenting with this locally and share a potential approach or draft PR for feedback?

nitin-999-code avatar Nov 11 '25 17:11 nitin-999-code

Sure, try it out!

vkarpov15 avatar Nov 13 '25 21:11 vkarpov15