首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在NestJs + Typegoose中将_id替换为id

在NestJs + Typegoose中将_id替换为id
EN

Stack Overflow用户
提问于 2020-03-23 05:03:46
回答 3查看 2.3K关注 0票数 3

我使用NestJs + Typegoose。如何在NestJs + Typegoose中将_id替换为id?我没有找到一个明确的例子。我尝试了一些东西,但没有任何结果。

代码语言:javascript
复制
@modelOptions({
  schemaOptions: {
    collection: 'users',
  },
})
export class UserEntity {
  @prop()
  id?: string;

  @prop({ required: true })
  public email: string;

  @prop({ required: true })
  public password: string;

  @prop({ enum: UserRole, default: UserRole.User, type: String })
  public role: UserRole;

  @prop({ default: null })
  public subscription: string;
}
代码语言:javascript
复制
@Injectable()
export class UsersService {
  constructor(
    @InjectModel(UserEntity) private readonly userModel: ModelType<UserEntity>,
  ) {}

  getOneByEmail(email: string) {
    return from(
      this.userModel
        .findOne({ email })
        .select('-password')
        .lean(),
    );
  }
}
EN

回答 3

Stack Overflow用户

发布于 2020-08-12 14:25:25

将默认_id更新为id的另一种方法是覆盖modelOptions装饰器中的toJSON方法。

代码语言:javascript
复制
@modelOptions({
    schemaOptions: {
        collection: 'Order',
        timestamps: true,
        toJSON: {
            transform: (doc: DocumentType<TicketClass>, ret) => {
                delete ret.__v;
                ret.id = ret._id;
                delete ret._id;
            }
        }
    }
})
@plugin(AutoIncrementSimple, [{ field: 'version' }])
class TicketClass {

    @prop({ required: true })
    public title!: string

    @prop({ required: true })
    public price!: number

    @prop({ default: 1 })
    public version?: number
}


export type TicketDocument = DocumentType<TicketClass>


export const Ticket = getModelForClass(TicketClass);
票数 2
EN

Stack Overflow用户

发布于 2020-03-23 21:41:07

我可以说这是底层的mongoose行为,或者你可以发送带有'id‘而不是'_id’的JSON,在你的所有模型上使用虚拟属性是一种非常安全和简单的方法。

举个例子:

代码语言:javascript
复制
export const NotesSchema = new Schema({
  title: String,
  description: String,
});

NotesSchema.virtual('id')
    .get(function() {
      return this._id.toHexString();
});

或者,您可以在执行此操作的模型上创建一个toClient()方法。这也是重命名/删除您不想发送给客户端的其他属性的好地方:

代码语言:javascript
复制
NotesSchema.method('toClient', function() {
    var obj = this.toObject();

    //Rename fields
    obj.id = obj._id;
    delete obj._id;

    return obj;
});
票数 0
EN

Stack Overflow用户

发布于 2021-04-07 05:03:06

在类转换器中使用typegoose:

代码语言:javascript
复制
import * as mongoose from 'mongoose';
import { Expose, Exclude, Transform } from 'class-transformer';

@Exclude()
// re-implement base Document to allow class-transformer to serialize/deserialize its properties
// This class is needed, otherwise "_id" and "__v" would be excluded from the output
export class DocumentCT {
  @Expose({ name: '_id' })
  // makes sure that when deserializing from a Mongoose Object, ObjectId is serialized into a string
  @Transform((value: any) => {
    if ('value' in value) {
      return value.value instanceof mongoose.Types.ObjectId ? value.value.toHexString() : value.value.toString();
    }

    return 'unknown value';
  })
  public id: string;

  @Expose()
  public createdAt: Date;

  @Expose()
  public updatedAt: Date;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60804946

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档