【发布时间】:2019-09-13 02:12:40
【问题描述】:
我正在尝试将以下内容从 pug 转换为 ejs。它是一个作者选择框(来自关联的集合),以将一本书添加到数据库的形式。当我添加一本新书时,它会引发错误“无法读取未定义的属性'_id'”指向第一个选项元素(但我可以出于某种原因更新现有的书)。而在哈巴狗版本中,它不会抛出这个错误。我的转换正确吗?
select#author.form-control(type='select', placeholder='Select author' name='author' required='true' )
- authors.sort(function(a, b) {let textA = a.family_name.toUpperCase(); let textB = b.family_name.toUpperCase(); return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;});
for author in authors
if book
option(value=author._id selected=(author._id.toString()==book.author._id.toString() ? 'selected' : false) ) #{author.name}
else
option(value=author._id) #{author.name}
我的转化:
<select class="form-control" id="author" type="select" placeholder="Select author" name="author" required="true">
<% authors.sort(function(a, b) {let textA = a.family_name.toUpperCase(); let textB = b.family_name.toUpperCase(); return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;}); %>
<% authors.forEach(function(author) { %>
<% if(typeof book !== 'undefined') { %>
<option value="<%= author._id %>" selected=<%= (author._id.toString() == book.author._id.toString()) ? 'selected' : 'false' %>><%= author.name %></option>
<% } else { %>
<option value="<% author._id %>"><%= author.name %></option>
<% } %>
<% }) %>
</select>
【问题讨论】: