[英]Node.js: how to deal with getFullYear in pug
我试图通过从 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;
});
作者 Controller:
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 像:
- 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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.