无法将类型'PersistEntityBackend a0'与'MongoContext'匹配 - 通过ObjectId获取文档

时间:2018-05-01 23:59:32

标签: mongodb haskell yesod

我试图为Yesod应用程序编写一个处理函数,它将ObjectId作为String,查询MongoDB集合,并返回与ObjectId匹配的文档。

documentation中有一个名为get的函数,它似乎正是这样做的,但此函数需要Key。再次咨询documentation我找到了一个将oidToKey转换为ObjectId的函数Key。把这一切放在一起,我的第一次尝试是这样的:

getMyEventR :: String -> Handler Value
getMyEventR oid = do
  let key = oidToKey (read oid :: ObjectId)
  Just myEvent <- runDB $ get key
  returnJson myEvent

但是

失败了
error:
• Couldn't match type ‘PersistEntityBackend a0’ with ‘MongoContext’
    arising from a use of ‘get’
  The type variable ‘a0’ is ambiguous
• In the second argument of ‘($)’, namely ‘get key’
  In a stmt of a 'do' block: Just myEvent <- runDB $ get key
  In the expression:
    do let key = oidToKey (read oid :: ObjectId)
       Just myEvent <- runDB $ get key
       returnJson myEvent

这引发了我this的问题,其中OP注意到您的Entity类型实际上有Key的实例;对我来说

newtype instance Key MyEvent = MyEventKey {unMyEventKey :: BackendKey MongoContext}

大!

let key = oidToKey (read oid :: ObjectId)
Just myEvent <- runDB $ get $ MyEventKey key
returnJson myEvent

都能跟得上:

    • Couldn't match expected type ‘BackendKey MongoContext’
              with actual type ‘Key record0’

啊,好吧,我需要一个BackendKey而不是Key。我们尝试使用toBackendKey

let key = toBackendKey (oidToKey (read oid :: ObjectId))
Just myEvent <- runDB $ get $ MyEventKey key
returnJson myEvent

再次,不:

    • Ambiguous type variable ‘record0’ arising from a use of ‘toBackendKey’
  prevents the constraint ‘(ToBackendKey
                              MongoContext record0)’ from being solved.
  Probable fix: use a type annotation to specify what ‘record0’ should be.

注释所有类型的所有方式都不起作用,现在我盲目地盯着错误。

对一个简单问题的详细解释:有人可以告诉我这里发生了什么吗?

0 个答案:

没有答案