【问题标题】:Express+mongoose: Populate data from array of objectExpress+mongoose:从对象数组中填充数据
【发布时间】:2018-09-10 18:06:19
【问题描述】:

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

我想在表格中显示数据,

猫鼬模型

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

谁能建议最好的方法?

【问题讨论】:

  • 这是Populate的错误用法,它用于引用其他集合中的文档。 sBranch 是银行架构/集合的一部分。
  • 你能举个例子吗
  • 具体的例子是什么?您是否查看了文档,它通常提供了很多信息。 mongoosejs.com/docs/populate.html

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


【解决方案1】:

你很接近。两个问题:

  1. .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

  1. 您对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
  });
});

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 2016-01-19
    • 2017-09-25
    • 1970-01-01
    • 2014-11-09
    • 2017-10-26
    • 2020-06-01
    • 2019-09-23
    • 2020-11-11
    相关资源
    最近更新 更多