Invalid BSON field value provided
This error occurs when an operation attempts to use a value of an incorrect or unsupported BSON type for a field. MongoDB's strict schema validation or data type constraints trigger this error when the provided data does not match the expected format.
- 1Providing a string where a number is expected in a document field, or vice-versa
- 2Using an unsupported data type like 'undefined' in a document field, which is not a valid BSON type
- 3Attempting to update a field with a value that violates a collection's defined schema validation rules
- 4Corrupted data being sent from the application layer due to a bug or incorrect data manipulation
An update operation tries to set a field to an invalid BSON type, such as `undefined`.
db.products.insertOne({ sku: "123-abc", price: 99.99 });
// The following update fails because 'undefined' is not a valid BSON type for a field value.
db.products.updateOne({ sku: "123-abc" }, { $set: { description: undefined } });expected output
MongoServerError: BSON field 'update.$set.description' is the wrong type 'undefined', expected types...
Fix 1
Sanitize Input and Use Correct Data Types
WHEN Always before performing any write or update operation.
// Correct: Use null to represent an empty or non-existent value.
db.products.updateOne(
{ sku: "123-abc" },
{ $set: { description: null } }
);Why this works
Always validate and sanitize application input to ensure all fields conform to valid BSON data types. Using `null` is the correct BSON-compatible way to represent a non-value, whereas JavaScript's `undefined` is not.
Fix 2
Implement Stricter Schema Validation
WHEN When you need to enforce data integrity and consistency at the database level.
db.createCollection("products", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["sku", "price"],
properties: {
sku: { bsonType: "string" },
price: { bsonType: "double" },
description: { bsonType: ["string", "null"] }
}
}
}
})Why this works
MongoDB's server-side schema validation feature rejects any insert or update operations that do not meet the specified criteria, preventing BadValue errors from occurring at the source and ensuring data quality.
✕ Remove or disable schema validation just to force a write operation through
Disabling validation rules undermines data consistency, pollutes the collection with malformed documents, and inevitably leads to more complex, data-related bugs in the application logic.
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev