0

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

2 回答 2

1

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

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

mongoose.plugin(accessibleFieldsPlugin, { 
  getFields: (schema) => Object.keys({...schema.paths,...schema.virtuals})
})
于 2021-04-19T21:40:55.490 回答
0

使用@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');

于 2021-03-25T07:25:34.770 回答