CRUD operations using Scalatra and Casbah
Domanda
I'm learning Scala and MongoDB and such am using Scalatra and Casbah as the framework for a simple web app.
It is a simple message board, the intention to learn CRUD operations in Casbah. Problems is I'm finding that when I list the messages I have no way to uniquely reference a record in MongoDB on the site.
My current code is below.
The issue I'm having is that a ObjectID cannot be cast into a string. But without a unique id for each row I cannot provide a delete function from the web page.
Is there a standard way of handling these things using Casbah? All the tutorials I've seen have ignored uniquely accessing records from a webpage or completely ignored scalatra and focused only on handling records from scala code.
indexController.scala
get("/msgs")
{
contentType = "text/html";
var list = new ListBuffer[Message]()
for (i <- coll.find())
{
var message = new Message();
message.author = i.getOrElse("author", "???").toString();
message.message = i.getOrElse("msg", "???").toString();
message.id = i.getOrElse("_id", "???").asInstanceOf[String];
list += message;
}
layoutTemplate("/Views/index.scaml",("list" -> list.toList));
}
index.scaml
%body
%h2
Messages
%br
%ul
-@ val list: List[domain.Message]
- for (l:domain.Message <- list)
%li
From: #{l.author}
\- #{l.message}
%form{:method => "DELETE", :action => "msg/#{l.id}"}
%input{:type => "submit", :value => "Delete"}
Soluzione
You cannot cast but you can render it as a String easilly after:
i.getAs[ObjectId]("_id") map (_.toString) getOrElse "???"
And in the template you could do this
#{l.id.toString}