如何修改sails中的所有模型以注入全局属性

我正在使用sails框架,并希望自动注入2个额外的属性,以在所有模型中共享:createdBy和updatedBy(要引用到用户模型的字段)。 为了达到这个目标,我正在写一个钩子,试图改变模型

return { initialize: function ( next ) { sails.after( 'hook:orm:loaded', function () { setUpModelsCommonAttributes( next ); } ); sails.on( 'hook:orm:reloaded', setUpModelsCommonAttributes ); } }; function setUpModelsCommonAttributes( cb ) { // load models and process them sails.modules.loadModels( function ( err, models ) { if ( err ) { return cb( err ); } Object.keys( models ).forEach( function ( identity ) { if ( models[ identity ].autoCreatedBy !== false ) { _.defaults( models[ identity ].attributes, { createdBy: { model: 'User', index: true } } ); } if ( models[ identity ].autoUpdatedBy !== false ) { _.defaults( models[ identity ].attributes, { updatedBy: { model: 'User', index: true } } ); } } ); if ( cb ) { cb(); } } ); } 

不幸的是,模型的修改没有反映出来,数据库也没有得到更新。

如何确保这些变化传播,我在这里失去了一些东西? 有什么build议?

我相信你可以通过编辑config/models.js设置默认属性。 这些设置将与您的模型合并。

 module.exports.models = { attributes : { updatedBy : /*...*/, createdBy : /*...*/ } }