问题描述
在 Express 和 Mongoose 中使用 CASL,当我使用 accessibleFieldsPlugin
时,结果中不包含虚拟字段。
这是一个错误,还是我必须做一些解决方法才能将它们也包括在内?在这种情况下,最好的做法是什么?
人物模型:
const personSchema = new mongoose.Schema({
fullName: {
type: String,required: true
},picture: {
type: String,....
},{
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');
解决方法
如果您全局配置插件,可能会更容易维护。
这样的东西会添加所有的虚拟道具(仅供参考,id 已经包含在内)。
mongoose.plugin(accessibleFieldsPlugin,{
getFields: (schema) => Object.keys({...schema.paths,...schema.virtuals})
})
,
使用@Stotskyi 帮助,我设法解决了这样的问题(如果有更好的代码,我非常感谢任何帮助):
const personSchema = new mongoose.Schema({
fullName: {
type: String,required: true
},picture: {
type: String,....
},{
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');