Node.js sails mongo createdAt日期不正确
我正在使用sails 0.12.0和sails mongo 0.12.3。我从“外部”开发人员那里接管了一个现有的应用程序 我注意到当前所有mongo集合中的“createdAt”日期是不正确的,而updatedAt日期是正确的。创建文档时,createdAt日期应自动生成为今天的日期和时间,但它似乎设置为过去的某个日期。updatedAt日期似乎与今天的日期具有正确的值 例如:Node.js sails mongo createdAt日期不正确,node.js,mongodb,sails.js,sails-mongo,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"), "update
"createdAt" : ISODate("2017-09-25T18:39:49.409Z"), "updatedAt" : ISODate("2017-09-25T18:39:59.021Z")
module.exports = {
attributes: {
}
};
attributes: {
createdAt: {
type: 'datetime',
defaultsTo: function() {return new Date();}
}
},
我如何解决这个问题?我注意到“models”目录中的文件都是空的,因此这似乎不是模型问题,因为不存在显式模型
例如:
"createdAt" : ISODate("2017-09-25T18:39:49.409Z"), "updatedAt" : ISODate("2017-09-25T18:39:59.021Z")
module.exports = {
attributes: {
}
};
attributes: {
createdAt: {
type: 'datetime',
defaultsTo: function() {return new Date();}
}
},
我尝试在其中一个模型文件中显式地设置createdAt日期(如类似问题所建议的),但是这不起作用
例如:
"createdAt" : ISODate("2017-09-25T18:39:49.409Z"), "updatedAt" : ISODate("2017-09-25T18:39:59.021Z")
module.exports = {
attributes: {
}
};
attributes: {
createdAt: {
type: 'datetime',
defaultsTo: function() {return new Date();}
}
},
你可以试着用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();
},
}
对于sails 1.n,在sails/config/models.js中,您可以尝试:
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' },
},
你在用蓝图吗?如果是这样,您可能会在这些github问题中发现一些有用的东西: