无法读取属性“ getDate”

时间:2018-06-20 09:59:25

标签: javascript node.js mongoose keystone

我正在为项目使用梯形失真校正。在“ Post”数据库中,有publishedDate,我想用下面的代码对其进行格式化。

function formatDate(date) {
    var monthNames = [
        "Ocak", "Şubat", "Mart",
        "Nisan", "Mayıs", "Haziran", "Temmuz",
        "Ağustos", "Eylül", "Ekim",
        "Kasım", "Aralık"
    ];

    var day = date.getDate();
    var monthIndex = date.getMonth();
    var year = date.getFullYear();

    return day + ' ' + monthNames[monthIndex] + ' ' + year;
}


var q = keystone.list('Post').model.findOne({
        state: 'published',
        slug: locals.filters.post,
    }).populate('author categories');

    q.exec(function (err, result) {
        Object.keys(result).forEach(function (key) {
            var element = result[key];              
            element.newDate = formatDate(element.publishedDate);
        });

        locals.data.post = result;
        next(err);
    });

});

当我运行项目时,发生错误。但是我知道'publishedDate'是一个Date值。

 Mongoose model 'error' event fired on 'Post' with error:
 Cannot read property 'getDate' of undefined TypeError: Cannot read property 'getDate' of undefined

2 个答案:

答案 0 :(得分:0)

根据您的代码:

var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();

您确定在date对象中确实有一个getDate()date.getMonth()getFullYear(),因为我没有看到您在哪里实例化日期{{1} }。

也许您可能想了解一下,这可能会有所帮助。

new Date()

答案 1 :(得分:0)

替换

var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();

进入

var day = new Date(date).getDate();
var monthIndex = new Date(date).getMonth();
var year = new Date(date).getFullYear();