node.js - 将node js查询结果分离成对象?

标签 node.js express mongoose handlebars.js

我有一个正在返回结果的 Node 查询。然而,在我看来, Handlebars 助手将整个数组视为一个结果:

  {{#if donations}}
     {{#each donations}}
        {{this}} is printing the entire set of donations!
     {{/each}}
  {{/if}}

{{this}} 打印整个数组集,而不是只打印网页上的一个对象:

{ owner: '5a6d4c99d6320c05223e0cdb', _id: 5a930456d5ff0809409d15d8, name: 'test', price: 24, description: 'please donate to our cause', enddate: null, __v: 0 },{ owner: '5a6d4c99d6320c05223e0cdb', _id: 5a9a0b601be9210796083c9b, name: 'please donate again', price: 150, description: 'medical condition', enddate: null, __v: 0 },

这是相关的路由器代码:

// GET user by username
router.get('/:username', function(req, res) {

  //var id = req.params.id;
  var username = req.params.username;

  User.getUserByUsername(username,function(err, user){
    const vm = user;
    var id = vm.id;

    Donation.getDonationsByUserId(id, function(err, donations){
      const vd = { donations };
      //console.log(vd);
      res.render('user', {donations: vd, user: vm});
    })
  });
});

这是它引用的模型函数:

module.exports.getDonationsByUserId = function(id, callback){
  return Donation.find({owner: id}, function(err, donations) {
    //ar query = {owner: id};
    return callback(err, donations);
  });
}

如何迭代每个单独的对象结果?

谢谢!

最佳答案

考虑如下的 JSON 结构,

{
  "donations": [
    {
      "owner": "5a6d4c99d6320c05223e0cdb",
      "_id": "5a930456d5ff0809409d15d8",
      "name": "test",
      "price": 24,
      "description": "please donate to our cause",
      "enddate": null,
      "__v": 0
    },
    {
      "owner": "5a6d4c99d6320c05223e0cdb",
      "_id": "5a9a0b601be9210796083c9b",
      "name": "please donate again",
      "price": 150,
      "description": "medical condition",
      "enddate": null,
      "__v": 0
    }
  ]
}

您可以使用以下模板结构。

{{#if donations}
  {{#each donations}}
    {{#each this}}
      {{this}} 
    {{/each}}
    is printing the entire set of donations!
  {{/each}}
{{/if}}

输出打印为,

  5a6d4c99d6320c05223e0cdb 
  5a930456d5ff0809409d15d8 
  test 
  24 
  please donate to our cause 

  0 
is printing the entire set of donations!
  5a6d4c99d6320c05223e0cdb 
  5a9a0b601be9210796083c9b 
  please donate again 
  150 
  medical condition 

  0 
is printing the entire set of donations!

使用 http://tryhandlebarsjs.com 进行测试

希望这有帮助。

关于node.js - 将node js查询结果分离成对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49290151/

相关文章:

javascript - 主干 .save() 上的 404 错误

node.js - 将 Express.js 2 迁移到 3,特别是 app.dynamicHelpers() 到 app.locals.use?

node.js - 连接到 atlas mongo 数据库

node.js - 使用 Express 和 Mongoose 时默认启用什么缓存

javascript - 如何在 $geoNear 之后填充子文档

javascript - Mongodb duplicate key error collection dup key : null

node.js - 使用函数外部回调中的数据

javascript - 我认为我没有正确有效地实现和使用可读流?

node.js - 加速 AngularJs 项目的 Travis-CI 依赖项安装

node.js - require() 在 module.exports 中不起作用