使用 Scalatra 和 Casbah 进行 CRUD 操作
我正在学习 Scala 和 MongoDB,并使用 Scalatra 和 Casbah 作为简单 Web 应用程序的框架。
是一个简单的留言板,打算学习Casbah中的CRUD操作。问题是我发现当我列出消息时我无法唯一引用网站上 MongoDB 中的记录。
我当前的代码如下。
我遇到的问题是 ObjectID 无法转换为字符串。但是如果每行没有唯一的 ID,我无法从网页提供删除功能。
是否有使用 Casbah 处理这些事情的标准方法?我见过的所有教程都忽略了从网页唯一访问记录或完全忽略 scalatra,而只关注处理来自 scala 代码的记录。
索引控制器.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));
}
索引.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"}
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"}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法进行强制转换,但可以轻松地将其呈现为字符串:
在模板中您可以执行此操作
You cannot cast but you can render it as a String easilly after:
And in the template you could do this