5

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

@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;
}
@Injectable()
export class UsersService {
  constructor(
    @InjectModel(UserEntity) private readonly userModel: ModelType<UserEntity>,
  ) {}

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

3 回答 3

2

另一种更新默认值_idid方法是覆盖 modelOptions 装饰器中的 toJSON 方法。

@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);



于 2020-08-12T06:25:24.810 回答
0

我可以说它是潜在的猫鼬行为您可以使用“id”而不是“_id”发送 JSON,所有模型上的虚拟属性是一种非常安全且简单的方法。

一个例子:

export const NotesSchema = new Schema({
  title: String,
  description: String,
});

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

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

NotesSchema.method('toClient', function() {
    var obj = this.toObject();

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

    return obj;
});
于 2020-03-23T13:41:06.550 回答
0

将 typegoose 与类转换器一起使用:

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;
}

于 2021-04-06T21:03:05.683 回答