Express + mongoose:从对象数组中填充数据

时间:2018-04-01 07:20:45

标签: node.js express mongoose handlebars.js mongoose-schema

我正在尝试发送名称和一个数组作为对车把页面的响应。

我想在表格中显示数据

猫鼬模型

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,并希望在一个表中打印,其中一个银行可以有多个分支。

有人能建议最好的方法吗?

1 个答案:

答案 0 :(得分:2)

你很亲密。两个问题:

  1. .populate()
  2. 的使用不正确

    如果您的架构定义为:

    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

    1. 您对res.render的来电将在您的猫鼬查询完成后执行之前。这将导致您定义的sBranch数组始终为空。下面给出了async-await示例,省略了错误处理:
    2. -

      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
        });
      });