Skip to content

Instantly share code, notes, and snippets.

@molekilla
Created March 28, 2012 22:32
Show Gist options
  • Save molekilla/2231130 to your computer and use it in GitHub Desktop.
Save molekilla/2231130 to your computer and use it in GitHub Desktop.
Escuelita de Scala - Parte 4b - mongodb with casbah
package services
import com.mongodb.casbah.Imports._
import com.mongodb.casbah.commons.conversions.scala._
import com.mongodb._
import com.mongodb.ServerAddress
import com.mongodb.util._
import scalaj.collection.s2j._
abstract trait RegpubDataUtil {
protected def getDocumentByFicha(ficha:String):String
}
trait DataModelService extends RegpubDataUtil {
val mongoCollection = MongoConnection()("webdata")("regpub")
protected def getDocumentByFicha(ficha:String):String = {
// RM: Indexamos ficha, primera vez que se ejecuta indexa y toma un tiempo en completar
mongoCollection.ensureIndex("ficha")
val cursor = mongoCollection.find(MongoDBObject("ficha" -> ficha))
// RM: Scala If statements are expressions , using Options to avoid try/catch
val document = if ( cursor.hasNext ) Some(cursor.next.asDBObject) else None
if ( document.isDefined )
{
JSON.serialize(document)
} else {
"{}"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment