【问题标题】:How to get _id of Models in Mongoose (Typescript)如何在猫鼬(打字稿)中获取模型的_id
【发布时间】:2021-11-11 05:07:36
【问题描述】:

我正在使用 Mongoose 为 mongodb 对象建模(node.js / nestJS)

目标

我希望暴露 POJO 中对象的 _id(由 MongoDB 自动创建)。因为我需要它们在客户端进行一些操作。 (识别相同的对象,...)

我尝试了什么

export type GroupDocument = Group & Document;

@Schema()
export class Group {
    @Prop({ required: true })
    name: string;
}

鉴于上面的代码,我可以在使用时访问_id

const group: GroupDocument = this.findOne();

这很好。在大多数情况下,我不想使用整个GroupDocument 对象,因为它有很多开销,建议尽可能使用LeanDocuments。但是当我在 GroupDocument 上调用 .lean() 时,_id 会丢失,我无法再访问它。

const group: = this.findOne().lean();

如果我像这样从 Documents 扩展我的组,它会起作用:

Group extends Document

但猫鼬不建议这样做

我也想过像这样将 _id 放入 POJO:

@Schema()
export class Group {

    _id: string;

    @Prop({ required: true })
    name: string;
}

但这在我看来不是一个理想的解决方案。

我想做的就是让在一个瘦对象上调用group.id / group._id 成为可能。有什么方法可以在不损害任何最佳实践的情况下实现这一目标?

【问题讨论】:

  • 我认为您也可以在创建模型时获取对象的 id

标签: node.js typescript mongodb mongoose nestjs


【解决方案1】:

您必须将_id定义为:

import { Schema } from 'mongoose';
_id: Schema.Types.ObjectId

要仅返回 '_id' 字段,您可以在数据库中使用 project 并返回 _id 字段

【讨论】:

    猜你喜欢
    • 2017-01-20
    • 1970-01-01
    • 2014-02-15
    • 2018-10-09
    • 1970-01-01
    • 2016-11-12
    • 2016-02-05
    • 2020-05-11
    • 2018-10-24
    相关资源
    最近更新 更多