【发布时间】:2020-04-28 03:24:51
【问题描述】:
介意我请教一些关于如何遍历以下 JSON 对象并将其放入 Handlebars 模板的建议吗?
我在这里找到了很多关于“Handlebars and looping through JSON”的类似问题,但是经过几个小时的阅读和尝试各种排列后,我很困惑。
如果我打印 {{resorts}},度假村对象就会出现在模板页面上。
我可以得到一个似乎与度假村内的文档数量相对应的项目符号列表。
但我的目标是获取每个属性名称的项目符号列表,但我无法做到这一点。
非常感谢您的任何帮助。
我的 JSON:
{ properties: {
Country: 'United States',
Name: 'Killington',
description: `blurb`
},
geometry: {
coordinates: [ -72.8032981, 43.6176027 ],
type: 'Point'
},
datePosted: 2020-01-10T12:07:00.340Z,
_id: 5e11cd71746ed55b54a760ec,
type: 'Feature'
},
{ properties: {
Country: 'United States',
Name: 'Jay',
description: `blurb`
},
geometry: {
coordinates: [ -72.8032981, 43.6176027 ],
type: 'Point'
},
datePosted: 2020-01-10T12:07:00.340Z,
_id: 5e11cd71746ed55b54a760ec,
type: 'Feature'
}
我的 MongoDB 模型 (resort.js)
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
const ResortSchema = new Schema ({
type: String,
properties:{
Country: String,
Name: String,
description: String
},
geometry: {
type: {
type: String,
enum: ['Point'],
required: true
},
coordinates: {
type: [Number],
required: true
}
},
datePosted: {
type: Date,
default: new Date()
},
image: String
})
const Resort = mongoose.model('Resort', ResortSchema);
module.exports = Resort
我的 JS
exports.home = async(req, res) => {
const Resort = require('../models/resort')
const resorts = await Resort.find({})
res.render('home', {resorts: resorts})
}
我的车把模板:
{{#if resorts}}
<ul>
{{#each resorts}}
<li>
{{properties.Name}}
</li>
{{/each}}
</ul>
{{/if}}
编辑: 如果我执行以下操作,我会得到 JSON 输出,但如果我尝试深入了解 properties.Name:
,仍然无法成功<ul>
{{#resorts}}
<li>
{{this}}
</li>
{{/resorts}}
</ul>
输出
{ properties: { Country: 'USA', Name: 'Killington', description: "blurb" }, geometry: { coordinates: [ -72.8032981, 43.6176027 ], type: 'Point' }, datePosted: 2020-01-10T12:07:00.340Z, _id: 5e11cd71746ed55b54a760ec, type: 'Feature' }
更新
目前正在尝试在 MongoDB 中创建 JSON 验证。可能与此有关。
【问题讨论】:
-
您是否尝试过将
this用作{{this.properties.Name}}? -
感谢@chridam 的建议。这让我得到了子弹。但不幸的是,这个名字没有通过。我也没有成功使用其他类似的变体,例如 {{ this.Name}} 或 {{Name}}。
标签: json mongodb mongoose handlebars.js express-handlebars