In this recipe, we will see how we can use record
to connect our Lift application to a MongoDB database.
Before starting with this recipe, you will need to install MongoDB on your computer. You can download the appropriate installer for your OS from http://www.mongodb.org/downloads, and you can find installation instructions specific to your OS at http://docs.mongodb.org/manual/installation/.
build.sbt
file and add the following dependencies:"net.liftweb" %% "lift-mongodb" % liftVersion % "compile->default" withSources(), "net.liftweb" %% "lift-mongodb-record" % liftVersion % "compile->default" withSources()
import
statements in the Boot.scala
file:import net.liftweb.mongodb.{DefaultMongoIdentifier, MongoDB} import com.mongodb.Mongo
Boot.boot
method:MongoDB.defineDb(DefaultMongoIdentifier, new Mongo, "liftbook")
Lift provides an efficient layer to integrate applications with MongoDB. You can see that creating a connection to a MongoDB database is easy, and it takes just one line of code: MongoDB.defineDb(DefaultMongoIdentifier, new Mongo, "liftbook")
.
The defineDb
method takes three arguments. The first one is an identifier and defines a JNDI name for the Mongo instance. This argument is used by Lift as a key of a HashMap of identifiers to addresses. Therefore, given an identifier, Lift can reach the correct Mongo instance.
The second argument is the Mongo instance new Mongo()
. You can see that we didn't pass any parameter when constructing the Mongo
object instance. This means that Lift will create a Mongo instance using localhost
as the host address and the default Mongo port, 27017
. Finally, the third parameter is the database name.
18.217.5.86