Zaid-Ajaj / LiteDB.FSharp

Advanced F# Support for LiteDB, an embedded NoSql database for .NET with type-safe query expression through F# quotations
MIT License
180 stars 22 forks source link

let a1 = Bson.deserialize<Album> result - LiteDB Hello World from a newbie #24

Closed srlopez closed 5 years ago

srlopez commented 5 years ago

This is my very first contact with LiteDB, and with F #. And I do not know how to collect the value of a Document after reading it from the DB. What is wrong with what I have done?

open System

open LiteDB
open LiteDB.FSharp

type Genre = Rock | Pop | K-Pop

[<EntryPoint>]
let main argv =
    let mapper = FSharpBsonMapper()
    use db = new LiteDatabase("simple.db", mapper)

    let albums = db.GetCollection<Album>("albums")

    let seventeen = 
        { Id = 1; 
          Name = "Hello World!";
          Genre = K-Pop;
          DateReleased = DateTime(2017, 8, 12) }

    albums.Insert(seventeen)

    // result : Album
    let result = albums.findOne <@ fun album -> album.Id = 1 @> 
    let a1 = Bson.deserialize<Album> result
    prinfn a1.Name
    0

The error on line let a1 = Bson.deserialize<Album> result is: error FS0001: The type 'Album' is not compatible with the type 'BsonDocument' [..../app.fsproj]

Thanks from a newbie

Zaid-Ajaj commented 5 years ago

Hello there @srlopez, You don't need to call Bson.deserialize<Album> on the result value because it is already deserialized from a document to an Album type. So just write:

open System

open LiteDB
open LiteDB.FSharp

type Genre = Rock | Pop | K-Pop

[<EntryPoint>]
let main argv =
    let mapper = FSharpBsonMapper()
    use db = new LiteDatabase("simple.db", mapper)

    let albums = db.GetCollection<Album>("albums")

    let seventeen = 
        { Id = 1; 
          Name = "Hello World!";
          Genre = K-Pop;
          DateReleased = DateTime(2017, 8, 12) }

    albums.Insert(seventeen)

    // result : Album
    let result = albums.findOne <@ fun album -> album.Id = 1 @> 
    printfn "%s" result.Name
    0
Zaid-Ajaj commented 5 years ago

Also, quotations should be optional, you write this instead:

let result = albums.findOne (fun album -> album.Id = 1)
printfn "Album %s" result.Name
srlopez commented 5 years ago

Thanks @Zaid-Ajaj

Zaid-Ajaj commented 5 years ago

No problem @srlopez let me know if you encounter any problem :)