如何在sequelize ORM Query中更改日期格式?

时间:2017-01-31 12:47:01

标签: javascript node.js orm sequelize.js

我有这个模型

var Loans = sequelize.define('Loans', {
    book_id: DataTypes.INTEGER,
    patron_id: DataTypes.INTEGER,
    loaned_on: DataTypes.DATE
}

查询如下所示。

Loans.findAll().then(function(loans) {
   res.render('book_detail', {loans: loans});
});

我的问题是,如何在查询结果中以loaned_on格式更改YYYY-MM-DD字段,并且不需要时间戳。

当前loaned_on字段值在html表单字段中显示为Sun Jan 29 2017 00:00:00 GMT+0000 (GMT),在db值中显示为2017-01-29 00:00:00.000 +00:00

顺便说一下,dbsqlite3

2 个答案:

答案 0 :(得分:3)

我认为更好的解决方案是使用sequelize的自定义getter。定义模型时,为执行所需转换的loaned_on字段添加一个getter。像这样:

var Loans = sequelize.define('Loans', {
    book_id: DataTypes.INTEGER,
    patron_id: DataTypes.INTEGER,
    loaned_on: {
        type: DataTypes.DATE,
        get: function(fieldName) {
            const rawValue = this.getDataValue('loaned_on');
            // parse raw value using whatever logic you want
            // this won't work, but you get the idea
            return moment(rawValue).toISOString();
        }
    }
}

此外,这个SO答案显示了如何修改数据库配置,以便按照您喜欢的方式存储日期(如果您使用的是postgres):

https://stackoverflow.com/a/48388996/814463

sqlite3可能有类似的选项。

答案 1 :(得分:1)

使用https://momentjs.com/docs/#/parsing/string-format/

Loans.findAll().then(function(loans) {
    loans = loans.map(function (loan) {
        loan.loaned_on = loan.loaned_on.getFullYear() + '-' + 
            (loan.loaned_on.getMonth() < 9 ? '0' : '') + 
            (loan.loaned_on.getMonth() + 1) + '-' + loan.loaned_on.getDate();
        return loan;
    });
    res.render('book_detail', {loans: loans});
});