Normal Relationship handling is the use of embedded documents. However, sometimes there is a need for relationsips beetween collections. There is a Relations Trait to be used in case classes for easy relationship handling.

Relations trait

The Relations trait extends DAO case classes with relationship functions.

  • relatedRecordForOneToOne (OneToOneRelationship and reference value needed)
  • relatedRecordsForOneToMany (OneToManyRelationship and reference value needed)


Simple Setup.

  • User Collection(should have one login and multiple friends)
  • Login Collection
  • Friend Collection

case class User(id: Long, name: String, loginId: String) case class Login(id: String, email: String, password: String) case class Friend(id: Long, name: String, userId: Long) object UserDAO extends MongoDAO[User](database, "user") object LoginDAO extends MongoDAO[Login](database, "login") object FriendDAO extends MongoDAO[Friend](database, "friend")

For relationship setup we create two Relationships in the UserDAO.

  • OneToOne loginRelation (LoginDAO, key is id in user collection)
  • OneToMany friendsRelation (FriendDAO, key is userId in friend collection)
sourceobject UserDAO extends MongoDAO[User](provider, "user") {
  lazy val loginRelation   = OneToOneRelationship(LoginDAO, "id")
  lazy val friendsRelation = OneToManyRelationship(SimplePersonDAO, "userId")

We extend the User case class with the Relations trait and add relation specific functions.

  • login (create an Option of Login)
  • friends (create a List of Friend)
sourcecase class User(id: Long, name: String, loginId: String) extends Relations {

  def login: Option[Login] = relatedRecordForOneToOne(UserDAO.loginRelation, loginId)

  def friends: List[SimplePerson] = relatedRecordForOneToMany(UserDAO.friendsRelation, id)