Connecting to MongoDB using record

In this recipe, we will see how we can use record to connect our Lift application to a MongoDB database.

Getting ready

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/.

How to do it...

  1. Start a new blank project.
  2. Edit the 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()
  3. Add the following import statements in the Boot.scala file:
    import net.liftweb.mongodb.{DefaultMongoIdentifier, MongoDB}
    import com.mongodb.Mongo
  4. Add the following line in the Boot.boot method:
    MongoDB.defineDb(DefaultMongoIdentifier, new Mongo, "liftbook")
  5. Start the MongoDB server.
  6. Start the application.

How it works...

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.

Note

The fact that Lift keeps this HashMap means that we can set more than one 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.

Note

It is really easy to use MongoDB on a Lift application. One line of code is all you need to connect your application to a MongoDB database.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.5.86