我正在尝试发送名称和一个数组作为对车把页面的响应。
我想在表格中显示数据
猫鼬模型
const Bank = new Schema({
sBankName: String,
sBranch: [
{
sBranchName: String,
sBranchDetail: String,
}
],
sBankDetail: String,
dCreatedDate: { type: Date, default: Date.now },
updated_at: { type: Date, default: Date.now }
});
路由器获取页面
router.get("/branch_data", isAdminOnly, ensureAuthenticated, (req, res) => {
var sBranch = [];
Bank.find({})
.populate("sBranch")
.exec(function(err, Bank) {
//var Bankf = JSON.stringify(Bank,null,"\t");
for (var i = 0; i <= Bank.length; i++) {
sBranch.push(Bank[i]);
}
});
console.log(sBranch);
res.render("branch_data", {
user: req.user,
admin: req.user.eUserType,
sBranch: sBranch
});
});
branch_data.handlebars
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>No.</th>
<th>Bank</th>
<th>Branch Name</th>
<th>Branch Detail</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{{sBranch}}
{{#each sBranch}}
<td>1</td>
<td>{{this.sBankName}}</td>
{{#each this.sBranch}}
<td>{{this.sBranch.sBranchName}}</td>
{{/each}}
<td>{{this.sBranch}}</td>
<td>
<textarea cols="50" rows="1" class="form-control" readonly></textarea>
</td>
</tr>
{{/each}}
</tbody>
</table>
我想从数据库中获取BankName,BranchName和Branchdetail,并希望在一个表中打印,其中一个银行可以有多个分支。
有人能建议最好的方法吗?
答案 0 :(得分:2)
你很亲密。两个问题:
.populate()
。如果您的架构定义为:
const Bank = new Schema({
sBankName: String,
sBranch: [{
type: Schema.Types.ObjectId,
ref: 'SomeOtherSchema'
}],
sBankDetail: String,
dCreatedDate: { type: Date, default: Date.now },
updated_at: { type: Date, default: Date.now }
});
然后你需要调用.populate('sBranch')
,这将为你提供完整的sBranch
对象。否则它只会给你和ObjectId
。
res.render
的来电将在您的猫鼬查询完成后执行之前。这将导致您定义的sBranch
数组始终为空。下面给出了async-await
示例,省略了错误处理:-
router.get("/branch_data", isAdminOnly, ensureAuthenticated, async (req, res) => {
// This is already an array. No need to loop and add to another array.
const sbranch = await Bank.find({}).exec();
res.render("branch_data", {
user: req.user,
admin: req.user.eUserType,
sBranch: sBranch
});
});