javascript - Node.js:如何处理 pug 中的 getFullYear
问题描述
我试图通过从 dateOfDeath 中减去 dateOfBirth 来获得寿命。getFullYear() 在控制台中返回年份。但是,在哈巴狗..它抛出错误如下:Cannot read property 'getFullYear' of undefined
寿命的作者模式:
AuthorSchema
.virtual('lifeSpan')
.get(function() {
const lifeSpan = (this.dateOfDeath.getFullYear() - this.dateOfBirth.getFullYear()).toString();
return lifeSpan;
});
作者控制器:
exports.authorList = async(req, res, next) => {
try {
await Author.find({}).exec((error, authorList) => {
if(error) return authorList;
// console.log(authorList);
res.render('./author/index', { title: 'Author List', authorList: authorList});
});
} catch (error) {
res.status(500).json({ message: error.message });
}
};
指数.pug:
ul
each author in authorList
li
a(href=author.url) #{author.name}
| (#{author.lifeSpan})
else
li There is No Author in The List.
任何帮助,将不胜感激。
解决方案
似乎 PUG 覆盖了“this”,虽然在运行时调用了虚拟字段的 getter,但“this”指的是别的东西。
所以作为一个解决方案试试这个,添加一个 PUG 函数,如:
- function getLifeSpan(author){ return author.lifeSpan; }
这样你的哈巴狗文件看起来像这样:
- function getLifeSpan(author){ return author.lifeSpan; }
ul
each author in authorList
li
a(href=author.url) #{author.name}
| (#{getLifeSpan(author)})
else
li There is No Author in The List.
推荐阅读
- python - 将 numpy 一维数组用于线性代数的最佳方法
- powershell - Sharepoint 搜索服务管理 - 使用 Powershell 获取系统状态
- python - Matplotlib:一张图中的多个堆叠图
- wix - 引导程序捆绑安装先决条件后的 Wixsharp 自定义 ManagedUI
- python - 如何在 python scrapy 中只获取文本
- kotlin - 如何使用 Kotlin 的谓词将列表拆分为子列表?
- javascript - 使用 Svelte 进行倒计时冻结
- asp.net-web-api - 从 WebAPI 项目中访问 GraphAPI(通过 Microsoft.Identity.Web)
- node.js - 在我已经安装了 node.js 之后我可以安装 nvm
- ios - 从 mp4 为 HLS 创建变体播放列表的有效方法