Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何修改sails中的所有模型以注入全局属性_Node.js_Sails.js - Fatal编程技术网

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

Node.js 如何修改sails中的所有模型以注入全局属性,node.js,sails.js,Node.js,Sails.js,我正在使用sails框架,并希望自动注入两个附加属性,以便在所有模型中共享:createdBy和updatedBy(要引用到用户模型的字段)。为了实现这一点,我正在编写一个钩子并试图修改模型 return { initialize: function ( next ) { sails.after( 'hook:orm:loaded', function () { setUpModelsCommonAttributes( next );

我正在使用sails框架,并希望自动注入两个附加属性,以便在所有模型中共享: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();
        }

    } );

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


如何确保这些变化的传播,我在这里错过了什么?有什么建议吗?

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

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

谢谢,成功了。当我不希望这些字段出现(在参考表中)时,我希望通过标志
autoUpdatedBy=false
autoCreatedBy=false
来控制每个模型,但这会起作用