sails-mongo createdAt日期不正确

时间:2019-02-04 21:52:21

标签: node.js mongodb sails.js sails-mongo

我正在使用Sails 0.12.0和Sails-mongo 0.12.3。我从“外部”开发人员那里接管了一个现有应用程序。

我注意到当前所有mongo集合中的“ createdAt”日期都是错误的,而updatedAt日期是正确的。创建文档时,createdAt日期应自动生成为今天的日期和时间,但是似乎将其设置为过去的某个日期。对于今天的日期,updatedAt日期似乎具有正确的值。

示例:

"createdAt" : ISODate("2017-09-25T18:39:49.409Z"), "updatedAt" : ISODate("2017-09-25T18:39:59.021Z")

如何解决此问题?我注意到“模型”目录中的文件全部为空,因此由于没有显式模型,因此这似乎不是模型问题。

示例:

module.exports = {
  attributes: {

  }
};

我尝试在其中一个模型文件中明确设置了createdAt日期(类似问题所建议),但这没有用。

示例:

  attributes: {
    createdAt: {
      type: 'datetime',
      defaultsTo: function() {return new Date();}
    }
  },

2 个答案:

答案 0 :(得分:1)

您可以尝试定义自己的createdAt。

在单个模型(api/models中,您不需要编写与createdAt或updatedAt相关的任何内容。

// api/models/SomeModel.js
module.exports = {
  attributes: {
    // createdAt: { type:'string' },  -> coment it out, or remove at all from here.
  }
};

将此添加到您的config/models.js

// config/models.js

module.exports.models = {
  migrate: 'safe',
  attributes: {
    createdAt: { type: 'string' },
    updatedAt: { type: 'string' },
    id: { type: 'string', columnName: '_id' }
  },

  beforeUpdate: function(values, next) {
    if(!values.updatedAt) values.updatedAt = new Date().toISOString();
    // this is my feature i am using if i want to explicity not trigger updatedAt.
    else if(values.updatedAt == 'no_update') delete values.updatedAt;
    else values.updatedAt = new Date(values.updatedAt).toISOString();
    next();
  },

  beforeCreate: function(values, next) {
    if(!values.updatedAt) values.updatedAt = new Date().toISOString();
    else values.updatedAt = new Date(values.updatedAt).toISOString();
    if(!values.createdAt) values.createdAt = new Date().toISOString();
    else values.createdAt = new Date(values.createdAt).toISOString();
    next();
  },
}

答案 1 :(得分:0)

对于Sails 1.n,在sails / config / models.js中,您可以尝试:

button.INVISIBLE