【问题标题】:Node.js: how to deal with getFullYear in pugNode.js:如何处理 pug 中的 getFullYear
【发布时间】: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


【解决方案1】:

看起来 PUG 覆盖了“this”,虽然在运行时调用了虚拟字段的 getter,但“this”指的是别的东西。

所以作为解决方案试试这个,添加一个 PUG 函数,如:

- function getLifeSpan(author){ return author.lifeSpan; }

让你的 pug 文件看起来像这样:

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

【讨论】:

  • 行得通!你能看看下面的问题吗? question
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-04
  • 2013-02-04
  • 1970-01-01
  • 1970-01-01
  • 2012-12-12
相关资源
最近更新 更多