ObjectId cross-version compatibility
Overview
monSQLize automatically normalizes compatible ObjectId values across BSON versions, so ObjectId objects from libraries such as mongoose can be used in MongoDB adapter reads and writes.
Problem background
When your project mixes multiple MongoDB libraries, you may encounter BSON version conflicts:
Root Cause:
- mongoose depends on
bson@4.xorbson@5.x - monSQLize uses
mongodb@6.xinternal dependencybson@6.x - The mongodb@6.x driver refuses to accept ObjectId instances other than
bson@6.x
Solution
monSQLize has built-in automatic cross-version ObjectId conversion function, without manual processing:
Automatic conversion
Working principle
monSQLize's convertObjectIdStrings function does:
- Detect old version ObjectId: Identified by
constructor.name === 'ObjectId' - Safe conversion: Call
.toString()to obtain the hexadecimal string, and then construct it into thebson@6.xversion - Recursive processing: Automatically handle ObjectId in nested objects and arrays
- Error downgrade: When the conversion fails, the original object is returned and other fields are not affected.
Supported scenarios
1. Single ObjectId
2. Nested objects
3. ObjectId array
4. Query conditions
Performance optimization
- Zero-copy optimization: If there is no ObjectId that needs to be converted in the object, return the original object (no cloning)
- Value-based detection: Valid ObjectId-looking values can be converted regardless of the field name.
- Cycle detection: Circular structures are detected to prevent infinite recursion.
Compatibility
Manual preprocessing (only when the application layer really needs it)
The public contract is automatic cross-version ObjectId conversion. Legacy helper subpaths are compatibility surfaces and are not recommended as formal dependency entry points.
If the business really needs to explicitly normalize the data before entering monSQLize, please do the preprocessing at the application layer and then hand the results to monSQLize; do not treat the old helper subpath as a long-term public API.
Debugging
The current v3 converter does not emit per-value conversion logs. To inspect conversion behavior, use an integration test, MongoDB command monitoring, or a focused unit test around the converter.
Notes
- Field references not converted: Field references (such as
$userId) in the MongoDB aggregation pipeline will not be converted - Special operators:
$expr,$function,$where, etc. are not converted internally - Circular Reference Detection: Automatically detect and prevent infinite recursion caused by circular references
- Error downgrade: When the conversion fails, the original value is returned and no exception is thrown.