我正在寻找一个与lift / mongodb一对一关系的简单例子。 我可以像这样创建一个简单的MongoRecord:
class Blob extends MongoRecord[Blob] with MongoId[Blob] {
def meta = Blob
object name extends StringField[Blob](this,10)
}
object Blob extends Blob with MongoMetaRecord[Blob]{
}
现在我想在Blob中添加父/子关系,我怎么能这样做?
编辑:
我最终找到了如何解决我的问题(这guide给了我很多帮助)。 结果如下:
MongoRecord:
package code.model
import net.liftweb.mongodb.record.{MongoMetaRecord, MongoRecord}
import net.liftweb.record.field.StringField
import net.liftweb.mongodb.record.field.{ObjectIdRefField, ObjectIdPk}
class Blob extends MongoRecord[Blob] with ObjectIdPk[Blob]{
def meta = Blob
object name extends StringField[Blob](this,10)
object child extends ObjectIdRefField(this,Blob)
}
object Blob extends Blob with MongoMetaRecord[Blob]
这是我创建和阅读记录的方式:
package code.lib
import net.liftweb.http._
import code.model.Blob
import net.liftweb.common.{Full}
object REST {
lazy val blob: LiftRules.DispatchPF = {
case Req("api" :: "blob" :: Nil, suffix, GetRequest) => {
() => {
val blobs = Blob.findAll.map(blob => {
val child = Blob.find(blob.child.is)
val childName = if (child.isDefined) child.open_!.name else "?"
<blob>
<id>{blob.id.is}</id>
<name>{blob.name}</name>
<child_name>{childName}</child_name>
</blob>
})
Full(XmlResponse(<blobs>{blobs}</blobs>))
}
}
case Req("api" :: "blob" :: Nil, suffix, PostRequest) => {
() => {
val randID = (scala.math.random * 999).toInt
val child = Blob.createRecord
child.name("child_" + randID)
child.save
val blob = Blob.createRecord
blob.name("blob_" + randID)
blob.child(child.id.is)
blob.save
Full(XmlResponse(<result>{blob.id.is}</result>))
}
}
}
}
我仍然不确定这是否是正确的方法,所以: 欢迎任何评论!
答案 0 :(得分:0)
你见过http://www.assembla.com/spaces/liftweb/wiki/Mongo_Record_Referenced_Objects吗? 看起来应该使用2.4-M1中的MongoRefField。