Skip to content

Conversation

@Vegapunk-debug
Copy link

@Vegapunk-debug Vegapunk-debug commented Nov 28, 2025

Fix: Prevent crash in Document.prototype.init() when called with null/undefined

Summary

Calling Document.prototype.init() with null or undefined currently throws a low-level
TypeError (Cannot read properties of null (reading '_id')). This PR adds an explicit
null/undefined check and throws a proper ObjectParameterError instead.

Motivation and Context

init() is part of the public API. While normally used internally, custom scripts or plugins
may pass invalid input. The new error message improves developer experience and prevents an
unexpected crash.

Reproduction

const mongoose = require('mongoose');
const doc = new mongoose.Document({}, new mongoose.Schema({ name: String }));

// Before:
// TypeError: Cannot read properties of null (reading '_id')
// doc.init(null);

// After:
// ObjectParameterError: Parameter "doc" to init() must be an object.
doc.init(null);

Testing

  • I have verified locally using the reproduction script above.
  • Also, ran npm test to ensure no regressions.

Kindly please review the pull request and merge it.

Thank you!

@Vegapunk-debug
Copy link
Author

@vkarpov15, Kindly please review the pull request.

Copy link
Collaborator

@vkarpov15 vkarpov15 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please undo unrelated formatting changes, this PR is impossible to review

@Vegapunk-debug
Copy link
Author

@vkarpov15 Thanks for the feedback!. I've reverted the unrelated formatting changes and updated the PR to include only the fix and a regression test. Ready for review.

Vegapunk-debug added a commit to Vegapunk-debug/mongoose that referenced this pull request Dec 3, 2025
Vegapunk-debug added a commit to Vegapunk-debug/mongoose that referenced this pull request Dec 3, 2025
@Vegapunk-debug
Copy link
Author

Hello @vkarpov15, I have made all the necessary changes. Please take a moment to review them.
Thank you !

Copy link
Collaborator

@vkarpov15 vkarpov15 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please undo all the unrelated formatting changes

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

Successfully merging this pull request may close these issues.

2 participants