diff --git a/Cookbook.md b/Cookbook.md index c7ea53e..05b5067 100644 --- a/Cookbook.md +++ b/Cookbook.md @@ -28,6 +28,7 @@ For non-Yesod code, see also [Snippets](https://github.com/yesodweb/yesod-cookbo * [Run raw MongoDB](https://github.com/yesodweb/yesod-cookbook/blob/master/cookbook/Rawmongo.md) * [Run raw SQL](https://github.com/yesodweb/yesod-cookbook/blob/master/cookbook/RawSQL.md) +* [Sample MongoDB connection with persistent](./cookbook/mongodb-example.md) * [Sphinx Search](https://github.com/yesodweb/yesod-cookbook/blob/master/cookbook/Sphinx-Search.md) * [Non scaffolded MongoDB App](https://github.com/yesodweb/yesod-cookbook/blob/master/cookbook/Non-scaffolded-MongoDB-App.md) * [Using Database.Persist.runPool without Foundation](https://github.com/yesodweb/yesod-cookbook/blob/master/cookbook/Using-Database.Persist.runPool-without-Foundation.md) diff --git a/cookbook/mongodb-example.md b/cookbook/mongodb-example.md new file mode 100644 index 0000000..e24966c --- /dev/null +++ b/cookbook/mongodb-example.md @@ -0,0 +1,86 @@ +# MongoDB Sample code with persistent + +``` haskell +#!/usr/bin/env stack +{- stack + --resolver lts-6.19 + --install-ghc + runghc + --package persistent + --package persistent-mongoDB + --package persistent-template + --package network + --package mtl +-} + +{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE EmptyDataDecls #-} +{-# LANGUAGE FlexibleContexts #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE GeneralizedNewtypeDeriving #-} +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE QuasiQuotes #-} +{-# LANGUAGE TypeFamilies #-} + +import Database.Persist +import Database.Persist.TH +import Database.Persist.MongoDB +import Control.Monad.Cont +import MongoImport +import Network (PortID(PortNumber)) +import Language.Haskell.TH (Type(..)) + +share + [mkPersist mongoSettings] + [persistLowerCase| +User + name String + age Int Maybe + deriving Show +Blogpost + title String + uid UserId + UniqueUser uid + deriving Show +|] + +main :: IO () +main = + withMongoDBConn + "myDatabaseName" + "localhost" + (PortNumber 27017) + Nothing + 2000 + (runMongoDBPool + master + (do user <- insert $ User "John Doe" $ Just 35 + liftIO $ print user + return ())) +``` + +You also have to have the `MongoImport.hs` modul along with it: + +``` haskell +{-# LANGUAGE TemplateHaskell #-} + +module MongoImport where + +import Language.Haskell.TH (Type(..)) +import Database.Persist.TH +import Database.Persist.MongoDB + +mongoSettings = + (mkPersistSettings (ConT ''MongoContext)) + { mpsGeneric = False + } +``` + +Execution demo: + +``` shellsession +sibi::jane { ~/scripts }-> ./mongodb.hs +UserKey {unUserKey = MongoKey {unMongoKey = 5801bde35844a10b1f000000}} +``` +