我正在使用一个向mongoose.model添加值的表单列出书目条目,但是某些条目需要有多个作者。
为了添加一个作者,我添加了一个分配给一个按钮的js脚本来添加作者的名字和名字的输入,但是当我提交表单而不是在一个模式中定义的对象数组中创建多个author对象时,它只是将所有的名字值和第二个名字的值都推入到同一个对象中。如何区分不同的作者,同时使用相同的输入向作者数组中添加多个author对象?
这是模式:
const BiblibliographySchema = new mongoose.Schema({
author: [{
firstName: "String",
secondName: "String"
}],
title: "String",
publishInfo: {
publisher: "String",
location: "String"
},
date: "Number"
});
module.exports = mongoose.model("Bibliography", BiblibliographySchema);以下是表格:
<form class="bibliography-form" action="/workspace/bibliography" method="POST">
<div id="add-input">
<input type="text" name="bibliography[author][firstName]"
placeholder="First Name">
<input type="text" name="bibliography[author][secondName]"
placeholder="Second Name">
<button id="add-name" type="button">+</button>
<br>
</div>
</form>这是添加输入字段的js脚本:
var button = document.getElementById("add-name");
button.addEventListener("click", function(){
var br = document.createElement('br');
document.getElementById("add-input").appendChild(br);
var input1 = document.createElement('input');
var input2 = document.createElement('input');
input1.setAttribute('type', 'text');
input1.setAttribute('name', 'bibliography[author][firstName]');
input1.setAttribute('placeholder', 'First Name');
input2.setAttribute('type', 'text');
input2.setAttribute('name', 'bibliography[author][secondName]');
input2.setAttribute('placeholder', 'Second Name');
document.getElementById("add-input").appendChild(input1);
document.getElementById("add-input").appendChild(input2);
document.getElementById("add-input").appendChild(br);
});这是一条创造路线:
app.post('/workspace/bibliography', function(req, res){
Bibliography.create(req.body.bibliography, function(err, newEntry){
if (err) {
console.log(err);
} else {
res.redirect('/workspace/bibliography');
}
});
});这是他的书目条目显示在页面上:
<div>
<% bibliography.forEach(function(entry){ %>
<form action="/workspace/bibliography/<%=entry._id%>?
_method=DELETE" method="POST">
<p>
<%= entry.author.secondName %>, <%= entry.author.firstName %>.
<i><%= entry.title %>. <%= entry.publishInfo.publisher %></i>,
<%= entry.publishInfo.location%>, <%= entry.date %>.
<button class="delete-bibliography-entry">x</button>
</p>
</form>
<% }); %>
</div>我希望输出结果如下:
但现在看起来是这样:
谢谢你的帮助!
发布于 2019-03-31 19:10:07
试着替换这一行
<%= entry.author.secondName %>, <%= entry.author.firstName %>。有了这个
<% for(var i=0; i<entry.author.secondName.length; i++) {%>
<%= entry.author.secondName[i] %>, <%= entry.author.firstName[i] %> /
<% } %>更新的:发布数据的方式是问题所在。它将所有输入处理为一个字符串,这就是为什么它将所有firstName和secondName存储在一个数组元素中,而不是多个数组元素中。发布对象数组的正确方法是发出AJAX请求。现在,如果您想找到一个快速的解决方案,您可以只使用一个输入(例如fullName)并显示全名。
https://stackoverflow.com/questions/55440811
复制相似问题