如何为Mongoose Schema字段添加自定义key并正确读取配置值?
解决方案
你在Mongoose Schema字段中添加的interface自定义配置属于Schema级的固定元数据,默认不会被挂载到文档实例的属性上,文档实例的title、body等属性存储的是实际的字段值(字符串类型),因此无法直接通过post.title.interface的形式访问配置。
你可以通过以下三种常用方案实现需求:
方案1:直接从Schema配置中读取(最推荐)
Mongoose会保留所有字段配置的自定义键,你可以通过Schema的path()方法直接读取对应字段的配置,无需修改原有业务逻辑:
// 读取单个字段的interface配置 const titleInterface = postSchema.path('title').options.interface; const bodyInterface = postSchema.path('body').options.interface; // 如果要从文档实例中读取,可直接调用实例的schema属性 post.schema.path('title').options.interface
如果需要批量获取所有字段的配置,遍历postSchema.paths对象即可。
方案2:封装实例方法简化调用
如果你需要频繁从文档实例中读取字段配置,可以给Schema添加自定义实例方法:
// 给Schema添加通用获取interface配置的方法 postSchema.methods.getInterface = function (fieldName) { return this.schema.path(fieldName)?.options.interface; } // 调用示例 const titleInterface = post.getInterface('title'); const bodyInterface = post.getInterface('body');
方案3:实现post.title.interface形式的访问(不推荐)
如果必须要实现你描述的访问形式,需要给字段添加getter,将字段返回值包装为同时包含实际值和配置的对象:
const postSchema = new mongoose.Schema({ title: { type: String, required: true, unique: true, interface: '<input type="text" name="title">', get: function (val) { return { value: val, interface: this.schema.path('title').options.interface } } }, body: { type: String, required: true, unique: false, interface: '<textarea name="body">...</textarea>', get: function (val) { return { value: val, interface: this.schema.path('body').options.interface } } } }, { // 开启getter的序列化,确保toJSON/toObject时也能拿到包装后的值 toJSON: { getters: true }, toObject: { getters: true } }) // 调用示例 const titleValue = post.title.value; // 实际的标题值 const titleInterface = post.title.interface; // 配置值
该方案会破坏原有字段的直接取值逻辑,需要修改所有原有读取字段值的代码,非特殊需求不建议使用。
内容的提问来源于stack exchange,提问作者Ayo Reis
相关产品推荐
相关产品推荐

