我使用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")如何解决此问题?我注意到" models“目录中的文件都是空的,所以这似乎不是一个模型问题,因为没有明确的模型存在。
示例:
module.exports = {
attributes: {
}
};我尝试在其中一个模型文件中显式设置createdAt日期(根据类似问题的建议),但是不起作用。
示例:
attributes: {
createdAt: {
type: 'datetime',
defaultsTo: function() {return new Date();}
}
},发布于 2019-02-06 14:34:20
你可以试着把自己定义为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();
},
}发布于 2019-09-28 17:40:44
对于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' },
},发布于 2021-11-02 20:40:36
在较新的Sails.js版本中(我猜是大于1.0,在1.5上进行了测试),它是这样工作的:
module.exports.models = {
createdAt: { type: 'ref', autoCreatedAt: true },
updatedAt: { type: 'ref', autoUpdatedAt: true },
}如果它是这样设置的,那么createdAt和updatedAt将如预期的那样成为MongoDB数据库中的ISODate()对象。
https://stackoverflow.com/questions/54524861
复制相似问题