Serialized List de-serializes back as a BasicDBList

378 views
Skip to first unread message

Warren Strange

unread,
Apr 15, 2011, 6:07:15 PM4/15/11
to mongodb-ca...@googlegroups.com

If I add a scala List element to a MongoDBObject, then persist it,  - it comes back on de-serialization as a BasicDBList. 


I would  like mongo lists elements to de-serialize to a Scala List.

Is there any way to avoid this - or do I just need to iterate through the object elements and do the conversion ? Would registering a custom handler work?

Thanks


Brendan W. McAdams

unread,
Apr 15, 2011, 6:19:29 PM4/15/11
to mongodb-ca...@googlegroups.com
BasicDBList has an implicit conversion to MongoDBList in scope (http://api.mongodb.org/scala/casbah/2.1.1/scaladoc/com/mongodb/casbah/commons/MongoDBList.html). MongoDBList is a LinearSeq[AnyRef].

As such you can call toArray, toBuffer, toIndexedSeq, toIterable, toIterator, toList, toSeq, toStream or toSet on a BasicDBList to get a more Scala-ey representation.

MongoDB stores lists internally as a Map[Int, AnyRef] so they have to be deserialized into an object that understands this interface.... for a variety of historical and safety reasons we don't explicitly convert it to a Seq or List on deser but provide conveniiences if you need it.

Warren Strange

unread,
Apr 16, 2011, 6:39:12 PM4/16/11
to mongodb-ca...@googlegroups.com

Thanks for the explanation Brendan

I dont think the implicit conversions are going to help in my case. My app wont always know the schema of the attributes coming back - so I have to test the data type and cast to right type. I somewhat (naively) thought that the collection data type would be preserved on deserialization- but I understand why that is difficult. 

Thanks again

Brendan W. McAdams

unread,
Apr 16, 2011, 6:40:34 PM4/16/11
to mongodb-ca...@googlegroups.com
There is another option.... which is to plug in a custom Type conversion which makes sure BSON Lists are deserialized as something you'd prefer: 

Warren Strange

unread,
Apr 18, 2011, 1:01:08 PM4/18/11
to mongodb-ca...@googlegroups.com


Tried that :-) No such luck 

I also use Salat to manage some object serialization - and I found that adding a type converter breaks Salat (it is expecting a DBList from the driver). 

I have managed to work around this problem by performing type conversion when I fetch non Salat objects from Mongo.

Long term  it would be great to see Casbah offer a "pure" Scala oriented interface without exposing Java driver objects (tall order I know... just puttin it out there :-) )

Brendan W. McAdams

unread,
Apr 18, 2011, 1:14:46 PM4/18/11
to mongodb-ca...@googlegroups.com

It's about 70% done ;)

Reply all
Reply to author
Forward
0 new messages