【发布时间】:2020-02-21 22:08:37
【问题描述】:
我试图通过从 dateOfDeath 中减去 dateOfBirth 来获得 lifeSpan。 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.
任何帮助将不胜感激。
【问题讨论】:
-
你能告诉我你提到的控制台日志结果是否正确
-
抱歉迟到了。控制台显示如下:
4338作为,我在 2 个集合中添加了 dateOfBirth 和 dateOfDeath。值显示在不同的行中。 -
看起来 PUG 覆盖了“this”,虽然在运行时调用了 virtual 的 getter,但“this”指的是别的东西
标签: javascript node.js express mongoose