如何解决“accessibleFieldsPlugin”不包括虚拟字段
在 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');
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。