首页 > 解决方案 > Haskell MongoDB 对象到 Bson

问题描述

我正在尝试从bson-mapping模块构建示例代码,但我无法弄清楚如何正确地做到这一点。

{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}

module Session where

import Data.Bson.Mapping
import Data.Time.Clock
import Data.Data (Typeable)

data Post = Post { time :: UTCTime
                 , author :: String
                 , content :: String
                 , votes :: Int
                 }
          deriving (Show, Read, Eq, Ord, Typeable)
$(deriveBson ''Post)

我收到以下错误:

/src/mapping/Session.hs:27:3: error:
    • Could not deduce (MonadFail m)
        arising from a use of ‘Data.Bson.lookup’
      from the context: Monad m
        bound by the type signature for:
                   fromBson :: forall (m :: * -> *).
                               Monad m =>
                               Data.Bson.Document -> m Post
        at src/mapping/Session.hs:27:3-19
      Possible fix:
        add (MonadFail m) to the context of
          the type signature for:
            fromBson :: forall (m :: * -> *).
                        Monad m =>
                        Data.Bson.Document -> m Post
    • In a stmt of a 'do' block:
        con_alkG <- (Data.Bson.lookup Data.Bson.Mapping.consField) doc_alkH
      In the expression:
        do con_alkG <- (Data.Bson.lookup Data.Bson.Mapping.consField)
                         doc_alkH
           case con_alkG :: Text of
             "Post" -> do ...
             _ -> fail "Couldn't find right constructor"
      In the expression:
        \ doc_alkH
          -> do con_alkG <- (Data.Bson.lookup Data.Bson.Mapping.consField)
                              doc_alkH
                case ... of
                  "Post" -> ...
                  _ -> ...
   |
27 | $(deriveBson ''Post)
   |   ^^^^^^^^^^^^^^^^^

我不确定这里有什么问题。先感谢您。

标签: mongodbhaskell

解决方案


问题是它bson-mapping已经 3 年没有更新并且不支持 GHC 8.8.1 和更新版本已完全实施的 MonadFail 提案。解决此问题的正确方法是更新bson-mapping并更改fromBson :: Monad m => Document -> m afromBson :: MonadFail m => Document -> m a. 理想情况下,上游会为您执行此操作,但您可以自己在本地分叉中执行此操作。或者,您可以降级到 GHC 8.6.5,它仍然允许旧的、危险的使用fail.


推荐阅读