【问题标题】:Virtual fields aren't included by "accessibleFieldsPlugin"“accessibleFieldsPlugin”不包含虚拟字段
【发布时间】:2021-06-18 06:30:02
【问题描述】:

将 CASL 与 Express 和 Mongoose 结合使用,当我使用 accessibleFieldsPlugin 时,结果中不包含虚拟字段。

这是一个错误,还是我必须采取一些解决方法才能将它们也包含在内?在这种情况下最好的做法是什么?

人物模型:

const personSchema = new mongoose.Schema({
    fullName: {
        type: String,
        required: true
    },
    picture: {
        type: String,
        required: true
    },
    ....
}, {
    timestamps: true,
    toObject: { virtuals: true },
    toJSON: { virtuals: true }
});

personSchema.virtual('picturePath').get(function () {
    if (this.picture != null) {
        return path.join('/', uploadPath, this.picture)
    }
    return null;
});

personSchema.plugin(accessibleRecordsPlugin);
personSchema.plugin(accessibleFieldsPlugin);

module.exports.Person = mongoose.model('Person', personSchema, 'person');

【问题讨论】:

标签: express mongoose casl


【解决方案1】:

如果全局配置插件,可能会更容易维护。

这样的东西会添加所有的虚拟道具(仅供参考,id 已经包含在内)。

mongoose.plugin(accessibleFieldsPlugin, { 
  getFields: (schema) => Object.keys({...schema.paths,...schema.virtuals})
})

【讨论】:

    【解决方案2】:

    使用@Stotskyi 帮助,我设法解决了这个问题(如果有更好的代码,我非常感谢任何帮助):

    const personSchema = new mongoose.Schema({
        fullName: {
            type: String,
            required: true
        },
        picture: {
            type: String,
            required: true
        },
        ....
    }, {
        timestamps: true,
        toObject: { virtuals: true },
        toJSON: { virtuals: true }
    });
    
    personSchema.virtual('picturePath').get(function () {
        if (this.picture != null) {
            return path.join('/', uploadPath, this.picture)
        }
        return null;
    });
    
    personSchema.plugin(accessibleRecordsPlugin);
    
    // Here is the new code
    const customAccessibleFieldsPlugin = new accessibleFieldsPlugin(personSchema, {
        getFields(schema) {
            const paths = Object.keys(schema.paths);
            paths.push('id');
            paths.push('picturePath');
            return paths;
        }
    });
    personSchema.plugin(() => customAccessibleFieldsPlugin);
    
    module.exports.Person = mongoose.model('Person', personSchema, 'person');
    
    

    【讨论】:

      猜你喜欢
      • 2012-07-18
      • 2020-05-18
      • 2012-08-30
      • 1970-01-01
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 2010-12-10
      相关资源
      最近更新 更多