How to Fix MongoDB Error 22 (InvalidBSON)
You see mongodb error 22 when the database gets a corrupt or malformed BSON document. You fix this InvalidBSON failure by checking client drivers, fixing bad data types, and validating network packets. MongoDB uses BSON to store documents and send messages over the wire. When a client sends bytes that break BSON rules, the server stops the request right away. The official spec lists code 22 under the ValidationError and ConnectionFatalMessageParseError categories. Because the server cannot trus
Your coding agents run with your access.
Claude Code reaches prod with a developer's credentials, and approval prompts get clicked through. hoop.dev checks every query, masks sensitive data, and holds risky changes for a human.
You see mongodb error 22 when the database gets a corrupt or malformed BSON document. You fix this InvalidBSON failure by checking client drivers, fixing bad data types, and validating network packets.
MongoDB uses BSON to store documents and send messages over the wire. When a client sends bytes that break BSON rules, the server stops the request right away. The official spec lists code 22 under the ValidationError and ConnectionFatalMessageParseError categories. Because the server cannot trust the message boundary, it often drops the client link too.
Root causes of mongodb error 22 in production
Most InvalidBSON errors start on the client side before the data reaches the server. An app might build raw byte buffers by hand instead of using the official driver. If the header size in the buffer does not match the real byte length, parsing fails. Bad UTF-8 strings in text fields also trigger this error code during document checks.
Network gear between the app and the cluster can also break valid BSON packets. A faulty network proxy or mismatched TLS setting might cut a packet short in flight. When the database reads the broken stream, it flags the message as a fatal parse error.
Corrupt data on disk is a less common cause of code 22. If a storage disk fails, a stored document might lose its closing byte. When a user runs a find action on that collection, the server hits the bad bytes. The query then fails and returns the InvalidBSON error to the client app.
How to diagnose and fix InvalidBSON safely
Start your check by looking at the server logs to find the failing client source. Check which app sent the bad payload and review its driver setup. Make sure the app uses a stable driver and does not edit raw BSON bytes directly. Validate all user inputs for proper UTF-8 encoding before the app sends writes.
MongoDB Authentication & Authorization + End-to-End Encryption: architecture patterns and best practices
Continue reading? Get the full guide.
Free. No spam. Unsubscribe anytime.
When you check collections on the server, use least privilege roles for your team. MongoDB grants access through role-based rules that apply to a specific database down to a collection. Give your team the built-in read role when they inspect data for corruption. The read role allows find, listCollections, listIndexes, dbStats, collStats, and changeStream actions on non-system collections. It blocks insert, update, remove, and dropCollection actions so no one breaks data during a check.
If you only need to add an index or change a collection, avoid full admin rights. Use the readWrite role only when you must fix bad documents with update or remove actions. While your team runs find queries to locate bad records, protect sensitive fields in the output. Data masking can rewrite matched fields like emails, phone numbers, card numbers, or national IDs in results. This keeps private user details safe while engineers inspect documents to fix the BSON error.
Preventing future BSON parse failures
You can stop code 22 from coming back by adding strict checks in your app pipeline. Let the official driver handle all BSON work instead of using custom byte encoders. Test network paths to make sure middle boxes do not change database traffic. Keep your database roles tight so human operators cannot send raw, unchecked writes to production collections.
Add command guardrails and field masking beside MongoDB
Collection roles and IP rules control who connects to MongoDB. Yet an active client or agent session can still run a pipeline that writes data or reads raw personal fields. In practice, hoop.dev sits inline in the wire protocol beside your database as a sidecar for your MongoDB. For every command an agent or human sends in production, hoop.dev decides to pass, mask, block, or escalate it for review.
Using hoop.dev MongoDB controls, guardrails refuse banned commands before they run or hold risky calls for approval, and data masking rewrites matched fields in returned documents in memory. Furthermore, hoop.dev holds SOC 2 Type II, is MIT licensed, and generates evidence for GDPR, HIPAA, and PCI DSS programs. View the project on GitHub.
Frequently asked questions
What does MongoDB error code 22 mean?
Error code 22 is named InvalidBSON in the official MongoDB error list. It means the server got a BSON document or network message with bad byte structure or invalid encoding.
Why does InvalidBSON drop the database link?
Code 22 belongs to the ConnectionFatalMessageParseError category in the database engine. When a message header is corrupt, the server cannot find the next message, so it closes the link.
Which role should engineers use to check collections for error 22?
Assign the built-in read role on the target database so engineers can run find and collStats safely. This role grants read access to non-system collections while blocking write actions like update, remove, or dropCollection.
Related guides
In this post