NestJS+MongoDB开发中如何实现数据库字段与服务端不同属性的映射
NestJS + MongoDB 字段自定义映射方案
以下是两种主流集成场景下的配置方案:
场景1:使用 @nestjs/mongoose(Mongoose ODM,最常用方案)
直接通过@Prop装饰器的name参数配置字段别名即可实现双向映射:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; @Schema() export class YourDocument extends Document { // 业务属性obj1映射数据库字段example1 @Prop({ name: 'example1' }) obj1: string; // 业务属性obj2映射数据库字段example2 @Prop({ name: 'example2' }) obj2: string; } export const YourSchema = SchemaFactory.createForClass(YourDocument);
- 配置完成后Mongoose会自动处理映射逻辑:
- 写入数据时,业务对象的
obj1/obj2值会自动存入数据库的example1/example2字段 - 查询数据时,数据库返回的
example1/example2字段会自动赋值给业务对象的obj1/obj2属性
- 写入数据时,业务对象的
- 如果使用
lean()查询返回原始JSON文档,未经过Mongoose序列化,可以配合class-transformer的@Expose装饰器做转换:
import { Expose } from 'class-transformer'; export class YourBizDto { @Expose({ name: 'example1' }) obj1: string; @Expose({ name: 'example2' }) obj2: string; } // 转换方法:const bizObj = plainToInstance(YourBizDto, rawMongoDoc);
场景2:使用 TypeORM 集成 MongoDB
通过@Column装饰器的name参数配置即可:
import { Entity, Column, ObjectIdColumn } from 'typeorm'; import { ObjectId } from 'mongodb'; @Entity() export class YourEntity { @ObjectIdColumn() id: ObjectId; @Column({ name: 'example1' }) obj1: string; @Column({ name: 'example2' }) obj2: string; }
配置完成后TypeORM会自动处理双向字段映射,无需额外操作。
注意事项
编写数据库聚合、原生查询等涉及原始字段的操作时,需要使用数据库实际存储的字段名example1/example2。
内容的提问来源于stack exchange,提问作者Harel Malichi
相关产品推荐
相关产品推荐

