Version 2.4-M1 introduces a new trait; MongoRefField. MongoRefField provides a obj method that retrieves the object from the database and caches it. It also provides a select element via the toForm method. You just need to override options. There are implementations for ObjectId, UUID, String, Int, and Long, but you can mix MongoRefField into any field.
import net.liftweb.mongodb._
class MainDoc private() extends MongoRecord[MainDoc] with ObjectIdPk[MainDoc] {
def meta = MainDoc
object name extends StringField(this, 12)
object refDocId extends ObjectIdRefField(this, RefDoc) {
override def options = RefDoc.findAll.map(rd => (Full(rd.id.is), rd.name.is))
}
}
object MainDoc extends MainDoc with MongoMetaRecord[MainDoc]
class RefDoc private() extends MongoRecord[RefDoc] with ObjectIdPk[RefDoc] {
def meta = RefDoc
object name extends StringField(this, 12)
}
object RefDoc extends RefDoc with MongoMetaRecord[RefDoc]
val ref1 = RefDoc.createRecord
.name("ref1")
.save
val md1 = MainDoc.createRecord
.name("md1")
.refDocId(ref1.id.is)
.save
assert(md1.refDocId.obj.map(_.id.is) == Full(ref1.id.is))
Note: There exists a DBRefField, but DBRef’s are no longer supported in MongoDB. It is recommended that you use one of the MongoRefField’s instead.