首页 > 解决方案 > 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.

任何帮助,将不胜感激。

标签: javascriptnode.jsexpressmongoose

解决方案


似乎 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.

推荐阅读