I used mongoDB and scala in my project using salat library and my model contains as :
case class ApplicationGroupModel(
@Key("_id") id: ObjectId,
devicesData: List[ApplicationDevicesData]
)
case class ApplicationDevicesData(
hostId: Option[String],
tcpPorts: List[Int] = List.empty,
applications: List[String] = List.empty)
object ApplicationGroupModel extends ModelCompanion[ApplicationGroupModel, ObjectId] {
val collection = ScalaMongoFactory.database(collectionName)
val dao = new SalatDAO[ApplicationGroupModel, ObjectId](collection = collection) {}
def apply(rawData: JsValue): ApplicationGroupModel = {
val devicesDataList = getTcpData(rawData)
ApplicationGroupModel(new ObjectId,devicesDataList)
}
private def getTcpData(rawData: JsValue): List[ApplicationDevicesData] = {
//function body
//return List of ApplicationDevicesData
}
and in controller I call model as :
val allData = ApplicationGroupModel.findOneById(new ObjectId("556c23b244aef072afcb6d50")).toList
If I print allData
it shows following output :
ApplicationGroupModel(556c23b244aef072afcb6d50,List(ApplicationDevicesData(Some(127.0.0.1),List(),List()), ApplicationDevicesData(Some(127.0.0.1),List(),List()), ApplicationDevicesData(Some(localhost),List(),List()))))
but If I call model
like this :
val allData = ApplicationGroupModel.collection.findOneByID(new ObjectId("556c23b244aef072afcb6d50")).toList
and print allData
then output as :
List({ "_id" : { "$oid" : "556c23b244aef072afcb6d50"} , "devicesData" : [ { "hostId" : "127.0.0.1" , "tcpPort" : [ 80 , 22 , 443] , "application" : [ "ABC"]} , { "hostId" : "127.0.0.1" , "tcpPort" : [ 22] , "application" : [ "XYZ"]} , { "hostId" : "localhost" , "tcpPort" : [ 5000 , 4100 , 22 , 80] , "application" : [ "ABCD"]}]})
I don't know why my model
find Method not return tcpPorts
with values it always empty lists same for applications
?
This is a simple naming problem. Your model object specifies tcpPorts
and applications
(plural) but your Mongo document has tcpPort
and application
(singular). Fix one or the other, or (not recommended since it will make your hand-written queries a pain, but it fixes your immediate problem) use @Key
with each field to map the singular to the plural.