{"record":{"id":"c95e9125b704ac43","repo":"litedb-org/LiteDB","slug":"value-is-not-a-valid-bson-data-type-use-mapper-t","errorCode":null,"errorMessage":"Value is not a valid BSON data type - Use Mapper.ToDocument for more complex types converts","messagePattern":"Value is not a valid BSON data type - Use Mapper\\.ToDocument for more complex types converts","errorType":"exception","errorClass":"InvalidCastException","httpStatus":null,"severity":"error","filePath":"LiteDB/Document/BsonValue.cs","lineNumber":189,"sourceCode":"\n                    this.Type = BsonType.Document;\n                    this.RawValue = dict;\n                }\n                else if (enumerable != null)\n                {\n                    var list = new List<BsonValue>();\n\n                    foreach (var x in enumerable)\n                    {\n                        list.Add(new BsonValue(x));\n                    }\n\n                    this.Type = BsonType.Array;\n                    this.RawValue = list;\n                }\n                else\n                {\n                    throw new InvalidCastException(\"Value is not a valid BSON data type - Use Mapper.ToDocument for more complex types converts\");\n                }\n            }\n        }\n\n        #endregion\n\n        #region Index \"this\" property\n\n        /// <summary>\n        /// Get/Set a field for document. Fields are case sensitive - Works only when value are document\n        /// </summary>\n        public virtual BsonValue this[string name]\n        {\n            get => throw new InvalidOperationException(\"Cannot access non-document type value on \" + this.RawValue);\n            set => throw new InvalidOperationException(\"Cannot access non-document type value on \" + this.RawValue);\n        }\n\n        /// <summary>","sourceCodeStart":171,"sourceCodeEnd":207,"githubUrl":"https://github.com/litedb-org/LiteDB/blob/f906a5f850678719e39a39a006cb66dcae563cfa/LiteDB/Document/BsonValue.cs#L171-L207","documentation":"Thrown by the BsonValue implicit-conversion constructor when the supplied object is not null and does not match any recognized BSON-compatible type (primitives, string, byte[], ObjectId, Guid, DateTime, IDictionary, IEnumerable, or another BsonValue). The message directs you to use BsonMapper.ToDocument for custom or complex types that need mapping logic. This is an InvalidCastException, not a LiteException.","triggerScenarios":"Wrapping a custom POCO, struct, tuple, enum, or any type not on the supported list in a `new BsonValue(myObject)` or assigning it where an implicit BsonValue conversion is expected.","commonSituations":"Passing a domain model object, a JObject/JToken, a tuple, or an enum directly into a BsonValue or BsonDocument field. Assigning a complex nested object without first mapping it through BsonMapper. Mixing JSON libraries (System.Text.Json / Newtonsoft) and feeding their DOM types into LiteDB.","solutions":["Map the object first: `BsonMapper.Global.ToDocument(myObject)` to convert a POCO into a BsonDocument.","Convert the value to a supported primitive before wrapping (e.g., cast enum to int, serialize JObject to a string or dictionary).","Register a custom type converter in BsonMapper if you need the type to be natively supported."],"exampleFix":"// before\nvar value = new BsonValue(myCustomerPoco);\n// after\nvar value = BsonMapper.Global.ToDocument(myCustomerPoco);","handlingStrategy":"validation","validationCode":"if (value != null && !IsBsonSupported(value))\n    value = BsonMapper.Global.ToDocument(value);\n\nstatic bool IsBsonSupported(object o) =>\n    o is int || o is long || o is double || o is decimal ||\n    o is string || o is byte[] || o is ObjectId || o is Guid ||\n    o is bool || o is DateTime || o is IDictionary ||\n    o is IList<BsonValue> || o is BsonValue || o is float[];","typeGuard":"static bool CanWrapAsBsonValue(object value) {\n    if (value == null) return true;\n    var t = value.GetType();\n    return t.IsPrimitive || t == typeof(string) || t == typeof(decimal) ||\n           t == typeof(byte[]) || t == typeof(DateTime) || t == typeof(Guid) ||\n           t == typeof(ObjectId) || t == typeof(float[]) ||\n           value is IDictionary || value is IList<BsonValue> || value is BsonValue;\n}","tryCatchPattern":"BsonValue bv;\ntry { bv = new BsonValue(obj); }\ncatch (InvalidCastException) { bv = BsonMapper.Global.ToDocument(obj); }","preventionTips":["Always map POCOs through BsonMapper.ToDocument before assigning to BsonValue.","Register custom type handlers in BsonMapper for domain-specific types.","Cast enums and nullable types to their BSON-compatible underlying representation explicitly."],"tags":["bson","type-conversion","invalid-cast","mapper"],"backgroundTag":null,"analyzedSha":"f906a5f850678719e39a39a006cb66dcae563cfa","analyzedAt":"2026-08-13T21:56:30.148Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}