首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >sails-mongo日期不正确

sails-mongo日期不正确
EN

Stack Overflow用户
提问于 2019-02-05 05:52:21
回答 3查看 414关注 0票数 0

我使用sails 0.12.0和sails-mongo 0.12.3。我从“外部”开发人员手中接管了一个现有的应用程序。

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

示例:

代码语言:javascript
复制
"createdAt" : ISODate("2017-09-25T18:39:49.409Z"), "updatedAt" : ISODate("2017-09-25T18:39:59.021Z")

如何解决此问题?我注意到" models“目录中的文件都是空的,所以这似乎不是一个模型问题,因为没有明确的模型存在。

示例:

代码语言:javascript
复制
module.exports = {
  attributes: {

  }
};

我尝试在其中一个模型文件中显式设置createdAt日期(根据类似问题的建议),但是不起作用。

示例:

代码语言:javascript
复制
  attributes: {
    createdAt: {
      type: 'datetime',
      defaultsTo: function() {return new Date();}
    }
  },
EN

回答 3

Stack Overflow用户

发布于 2019-02-06 14:34:20

你可以试着把自己定义为createdAt。

在您的单一模型(api/models)中,您不需要编写任何与createdAt或updatedAt相关的代码。

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

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

代码语言:javascript
复制
// 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
EN

Stack Overflow用户

发布于 2019-09-28 17:40:44

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

代码语言:javascript
复制
attributes: {
  createdAt: { type: 'string', columnType: 'datetime', autoCreatedAt: true, },
  updatedAt: { type: 'string', columnType: 'datetime', autoUpdatedAt: true, },
  // id: { type: 'number', autoIncrement: true, },
  id: { type: 'string', columnName: '_id' },
},
票数 0
EN

Stack Overflow用户

发布于 2021-11-02 20:40:36

在较新的Sails.js版本中(我猜是大于1.0,在1.5上进行了测试),它是这样工作的:

代码语言:javascript
复制
module.exports.models = {
    createdAt: { type: 'ref', autoCreatedAt: true },
    updatedAt: { type: 'ref', autoUpdatedAt: true },
}

如果它是这样设置的,那么createdAt和updatedAt将如预期的那样成为MongoDB数据库中的ISODate()对象。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54524861

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档