[英]How to get _id of Models in Mongoose (Typescript)
我正在使用 Mongoose 到 model mongodb object (node.js / nestJS)
我想要公開 POJO 中 object 的_id
- 它由 MongoDB 自動創建。 因為我需要在客戶端進行某些操作。 (識別相同的對象,...)
export type GroupDocument = Group & Document;
@Schema()
export class Group {
@Prop({ required: true })
name: string;
}
鑒於上面的代碼,我可以在使用時訪問_id
const group: GroupDocument = this.findOne();
這很好。 在大多數情況下,我不想使用整個GroupDocument
object,因為它有很多開銷,建議盡可能使用LeanDocuments
。 但是當我在 GroupDocument 上調用.lean()
時, _id
丟失並且我無法再訪問它。
const group: = this.findOne().lean();
如果我像這樣從 Documents 擴展我的組,它會起作用:
Group extends Document
但這不是 mongoose 推薦的
我還考慮過像這樣將 _id 放入 POJO 中:
@Schema()
export class Group {
_id: string;
@Prop({ required: true })
name: string;
}
但這在我看來不是一個理想的解決方案。
我想要做的就是在精益 object 上調用group.id
/ group._id
成為可能。有沒有什么方法可以在不損害任何最佳實踐的情況下實現這一目標?
您必須將 _id 定義為:
import { Schema } from 'mongoose';
_id: Schema.Types.ObjectId
要僅返回 '_id' 字段,您可以在數據庫中使用項目並返回 _id 字段
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.