简体   繁体   English

“accessibleFieldsPlugin”不包含虚拟字段

[英]Virtual fields aren't included by “accessibleFieldsPlugin”

Using CASL with Express and Mongoose, when I use accessibleFieldsPlugin , the virtual fields aren't included with the results.将 CASL 与 Express 和 Mongoose 一起使用,当我使用accessibleFieldsPlugin时,结果中不包含虚拟字段。

Is this a bug, or I have to do some workaround to get them included also?这是一个错误,还是我必须采取一些解决方法才能将它们也包括在内? What is the best thing to do in this situation?在这种情况下,最好的办法是什么?

Person model:人 model:

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');

It might be easier to maintain if you configure the plugin globally.如果您全局配置插件,可能会更容易维护。

Something like this would add all the virtual props (FYI, id is already included).像这样的东西会添加所有的虚拟道具(仅供参考,id 已经包括在内)。

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

Using @Stotskyi help, I manage to solve this problem like this (If there is a better code, I highly appreciate any help):使用@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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM