Express 虚拟字段不是';t包括在“;“可访问的现场布线”;

Express 虚拟字段不是';t包括在“;“可访问的现场布线”;,express,mongoose,casl,Express,Mongoose,Casl,将CASL与Express和Mongoose一起使用时,当我使用accessibleFieldsPlugin时,结果中不包括虚拟字段 这是一个bug,还是我必须做一些变通来把它们也包括进来?在这种情况下最好做什么 人物模型: const personSchema = new mongoose.Schema({ fullName: { type: String, required: true }, picture: { typ

将CASL与Express和Mongoose一起使用时,当我使用accessibleFieldsPlugin时,结果中不包括虚拟字段

这是一个bug,还是我必须做一些变通来把它们也包括进来?在这种情况下最好做什么

人物模型:

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

使用@Stotskyi help,我成功地解决了这个问题(如果有更好的代码,我非常感谢您的帮助):


如果全局配置插件,那么维护起来可能会更容易

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


您可以提供自定义的
getFields
选项来访问
accessibleFieldsPlugin
:。它接受mongoose模式,您可以使用它来检索字段
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');

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