我在使用序列化程式正確公開 _id 時遇到問題。
我用:
@UseInterceptors(ClassSerializerInterceptor)
@SerializeOptions({ strategy: 'excludeAll' })
定義的類:
export class UpdatedCounts {
@Expose()
_id: ObjectId;
@Expose()
aCount: number;
@Expose()
bCount: number;
constructor(partial: Partial<MyDocument>) {
Object.assign(this, partial);
}
}
console.log() 中的物件在它通過序列化程式運行之前
{
_id: new ObjectId("61c2256ee0385774cc85a963"),
bannerImage: 'placeholder2',
previewImage: 'placeholder',
aCount: 1,
bCount: 0,
}
回傳的物件:
{
"_id": {},
"aCount": 1,
"bCount": 0
}
那么我的 _id 怎么了?
我嘗試使用字串型別而不是 ObjectId 但這也不起作用
我不想使用@Exclude,因為我在示例 console.log() 中遺漏了另外 10 個道具,并且應該更容易排除所有道具并僅使用這 3 個
uj5u.com熱心網友回復:
只需使用@Transform:
@Expose()
@Transform((params) => params.obj._id.toString())
_id: ObjectId;
你不能只用 JSON 發送 ObjectId。您必須將其轉換為字串。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/389729.html
標籤:javascript 节点.js MongoDB 猫鼬 嵌套
