gpt4 book ai didi

mongodb - 斯科蒂使用 MongoDB

转载 作者:可可西里 更新时间:2023-11-01 09:10:54 26 4
gpt4 key购买 nike

我对 Haskell 比较陌生,这是我第一次使用 monad 转换器。非常感谢您的帮助。

runQuery :: Pipe -> Query -> ActionM (Either Failure [Document])
runQuery pipe query = access pipe master "nutrition" (find query >>= rest)

main = do
pipe <- runIOE $ connect $ host "127.0.0.1"

scotty 3000 $ do
post "/" $ do
b <- body
let user :: Either String User = eitherDecode b
case user of
Left err -> text . pack $ "Could not decode the user:" ++ err ++ ":\n" ++ (show b)
Right u -> do
let query::Query = (select ["i_name" =: ["$in" =: map (unpack . name) (foods u)]] "stock_foods")
results <- runQuery pipe query
...

我正在尝试查询 scotty 网络框架下的 mongodb 数据库,但我收到有关 MonadBaseControl 的错误。我真的必须为此创建一个实例才能使用 scotty 连接到数据库吗?我将如何去做?

No instance for (MonadBaseControl
IO (scotty-0.7.2:Web.Scotty.Types.ActionT Text IO))
arising from a use of `find'
Possible fix:
add an instance declaration for
(MonadBaseControl
IO (scotty-0.7.2:Web.Scotty.Types.ActionT Text IO))

最佳答案

mongoDB足够通用,可以在作为 MonadBaseControl IOMonadIO 实例的任何 monad 中工作。

例如,您可以选择IO monad。在这种情况下,您需要 liftIO 。在 scotty 的操作中运行查询:

import Web.Scotty
import Database.MongoDB
import qualified Data.Text.Lazy as T
import Control.Monad.IO.Class

runQuery :: Pipe -> Query -> IO [Document]
runQuery pipe query = access pipe master "nutrition" (find query >>= rest)

main = do
pipe <- connect $ host "127.0.0.1"
scotty 3000 $ do
get "/" $ do
res <- liftIO $ runQuery pipe (select [] "stock_foods")
text $ T.pack $ show res

@Sebastian Philipp 之后added MonadBaseControl Scotty.ActionT 的实例,不需要解除任何东西。您可以透明地使用 mongoDB 表单 scotty。只需更改类型签名并删除 liftIOs:

runQuery :: Pipe -> Query -> ActionM [Document]
...
get "/" $ do
res <- runQuery pipe (select [] "stock_foods")
text $ T.pack $ show res

关于mongodb - 斯科蒂使用 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23531465/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com