F# with LiteDB [<BsonIgnore>] is Ignored?

Context: Running F# in a containerized environment

$ dotnet --version 2.2.203
$ uname -a
Linux SAFE 4.15.0-48-generic #51-Ubuntu SMP Wed Apr 3 08:28:49 UTC 2019 x86_64 GNU/Linux

on Ubuntu 18.04 desktop machine.

This simple code ignores the [<BsonIgnore>] attribute. The value of Ignore is stored in LiteDB. Am I doing something wrong?
I’ve checked it by looking with the console command $ dotnet LiteDB.Shell.dll micompany.db:

...
> open micompany.db
> db.computers.find
[1]: {"_id":11,"Ignore":"ignore","Manufacturer":"Computers Inc.","Disks":[{"SizeGb":100},{"SizeGb":250},{"SizeGb":500}]}

This is the code:

open System
open LiteDB
open LiteDB.FSharp

[<StructuredFormatDisplay("{SizeGb}GB")>]
[<CLIMutable>]
type Disk = 
    { SizeGb : int }

[<StructuredFormatDisplay("Computer #{Id}: {Manufacturer}/{Disks}")>]
[<CLIMutable>]
type Computer =
    { Id: int
      [<BsonIgnore>] Ignore : string
      Manufacturer: string
      Disks: Disk list }

[<EntryPoint>]
let main argv =

    let myPc =
        { Id = 0
          Ignore = "ignore"
          Manufacturer = "Computers Inc."
          Disks =
            [ { SizeGb = 100 }
              { SizeGb = 250 }
              { SizeGb = 500 } ] }

    let mapper = FSharpBsonMapper()
    use db = new LiteDatabase("micompany.db", mapper)
    let computers = db.GetCollection<Computer>("computers")

    // Insert & Print
    computers.Insert(myPc) |> ignore
    printfn "%A" myPc

    0 // return an integer exit code

On the other hand, the [<StructuredFormatDisplay>] attribute of the Disk record is not correctly written (only a few dots appear in the console), when the Computer record is printed with printfn "%A" myPc. The output is:

Computer #12: Computers Inc./[...GB; ...GB; ...GB]

Is there anything else I need to say?

1 Like

The problem is that the json converter that’s used to power the bson deserialization doesn’t take that attribute into account when writing your type to json. The json converter can be found here, and specifically in the WriteJson member you can see that there’s no handling of the BsonIgnore attribute. You should raise an issue on the repo if this support is important to you. The hardest part I could see about supporting it is what value to assign to your field when the document is read from the database. F# records always have to have valid values for all fields, and if you don’t send a value to the database what should be used in its place?

3 Likes

Thanks @chethusk.
Your are right, but the only case where I see utility for [<BsonIgnore<] is when the value is a value calculated based on other values ​​(members / properties / etc …).
That way I have a record or class closer to a classic OOP object.

Issue requested