【发布时间】:2019-04-12 02:16:07
【问题描述】:
我有一个使用 Express 在 Node.js 中运行的应用程序,我想使用 jquery 动态更改选择对象的选项。这实际上不是一个大问题,但是我在脚本标签中使用 res.render 参数(它们是猫鼬文档)时遇到了麻烦。我在 html 上使用它们没有任何问题(实际上是翡翠),但是在脚本标签中我遇到了 ObjectId 不是字符串的问题。
这是代码的摘录: 在后端:
router.get("/new", function(req, res){
res.render("session/documentos/new",
{
services: res.locals.services
});
});
在视图中
block content
div
h1(class="text-center") New document
form(id="newDoc" action="/session/documentos" method="POST")
div(class="tab") Service:
div(class="form-group")
select(class="form-control" name="svc" id="svc")
option(value="undefined" disabled selected) Choose one
for service in services
option(value=service._id)=service.name
script.
$(document).ready(function() {
var sessLenght = 0;
var selectedSvc = #{services};
$("#svc").change(function(){
console.log("Service changed: " + selectedSvc);
});
});
这是我得到的错误: Console error
在来源中: Source error on ObjectId
所以我可以毫无问题地使用“服务”文档集合,但是当尝试在脚本标签上使用它们时,我遇到了 ObjectId 元素的问题。
我在想一种解决方案是在查询数据库时将 ObjectId 转换为字符串,但我认为可能有更简洁的解决方案。哪种方法可能是解决问题的最佳方法?
任何想法表示赞赏!提前致谢
【问题讨论】:
-
为什么首先要有
selectedSvc?选项的值为_id,足以在表单被退回快递时找到服务。你的脚本有什么意义? -
你好克里斯。是的,当然我可以在后端找到带有 id 的文档,问题是我想用服务文档中的信息填充 select html-object 中的选项。我想从脚本中读取服务文档中的信息以在视图中进行更改。我会检查链接,谢谢!
标签: javascript node.js mongoose pug objectid