我使用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(),
);
}
}发布于 2020-08-12 14:25:25
将默认_id更新为id的另一种方法是覆盖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-03-23 21:41:07
我可以说这是底层的mongoose行为,或者你可以发送带有'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;
});发布于 2021-04-07 05:03:06
在类转换器中使用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;
}https://stackoverflow.com/questions/60804946
复制相似问题