Created
November 26, 2012 10:16
-
-
Save agnaldo4j/4147509 to your computer and use it in GitHub Desktop.
MongoDB with scala and casbah
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package models.nereida | |
import scala.collection.mutable.ArrayBuffer | |
import com.mongodb.casbah.Imports._ | |
import scala.collection.JavaConversions._ | |
import org.bson.types.ObjectId | |
trait ManageCities { | |
def addCity(city:City):City = { | |
val newState = city.state + ("_id" -> new ObjectId()) | |
citiesCollection += newState | |
City(newState) | |
} | |
def cities():List[City] = { | |
val list:ArrayBuffer[City] = new ArrayBuffer[City](); | |
citiesCollection.find.foreach { cada => list += City(cada) } | |
list.toList | |
} | |
def findCityById(id:String):Option[City] = { | |
citiesCollection.findOneByID(id).map { city => | |
Some[City](City(city)) | |
}.getOrElse { | |
Some[City](null) | |
} | |
} | |
def removeCityById(id:String):Option[City] = { | |
findCityById(id).map { city => | |
citiesCollection.remove(city.state) | |
Some(city) | |
}.getOrElse { | |
Some[City](null) | |
} | |
} | |
def updateCityById(id:String, name:String):Option[City] = { | |
findCityById(id).map { city => | |
city.state.put("name", name) | |
citiesCollection.save(city.state) | |
Some(city) | |
}.getOrElse { | |
Some[City](null) | |
} | |
} | |
def mongoConnection(): MongoConnection = MongoConnection("host") | |
def mongoDB(): MongoDB = { | |
val mongodb:MongoDB = mongoConnection()("nereida") | |
mongodb.authenticate("user", "pwd") | |
mongodb | |
} | |
def citiesCollection(): MongoCollection = { | |
mongoDB()("cities") | |
} | |
implicit def dbObjectToMap(dbObject:DBObject): Map[String,AnyRef] = { | |
dbObject.toMap.asInstanceOf[Map[String,AnyRef]] | |
} | |
implicit def map2DBObject(state:Map[String,AnyRef]): DBObject = { | |
MongoDBObject(state.toList).asDBObject | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment