Tag Archives: lift

Example of a MongoCaseClassListField in Lift

Here’s a couple of hours days I’d like to get back: figuring out how to use the Lift Web Framework‘s oh-so-elusive and yet alluring MongoCaseClassLiftField  class. The idea seems just too wonderful to be true: you can store pretty much any object into a list, save it as a document in Mongo and get it back, pristine.

Of course, by “any object”, I mean any set of data you want to define. The objects have to be made in the Scala way: case classes that all inherit from a common regular class or trait.

In this example, I’m going to store different kinds of animals inside of a list.

You must override the  formats  variable in the way shown above, and you must set it INSIDE of the  MongoCaseClassListField  object, otherwise Very Bad Things will happen.

Now, you can do this:

Notice how, even though Dog and Cat have the same fields, Lift stores each object back to its proper type. This is because Lift has placed type hints inside of Mongo in extra “jsonClass” fields (you can override the name of the field if you need to):

So now, you can easily take advantage of Mongo’s document system and Scala’s type classes for pretty much free.