简体   繁体   English

如何在 Mongoose 中获取模型的 _id(打字稿)

[英]How to get _id of Models in Mongoose (Typescript)

I'm using Mongoose to model mongodb object (node.js / nestJS)我正在使用 Mongoose 到 model mongodb object (node.js / nestJS)

Goal目标

I want to have the _id - which is automatically created by MongoDB - of an object in a POJO exposed.我想要公开 POJO 中 object 的_id - 它由 MongoDB 自动创建。 Because I need them on client side for some operations.因为我需要在客户端进行某些操作。 (identify same objects, ...) (识别相同的对象,...)

What I tried我试过的

export type GroupDocument = Group & Document;

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

Given the code above, I can access the _id when I use鉴于上面的代码,我可以在使用时访问_id

const group: GroupDocument = this.findOne();

which is fine.这很好。 In most of the cases I don't want to work with the whole GroupDocument object, because it has a lot of overhead and it's recommended to work with LeanDocuments as much as possible.在大多数情况下,我不想使用整个GroupDocument object,因为它有很多开销,建议尽可能使用LeanDocuments But when I call .lean() on a GroupDocument, the _id gets lost and I can't access it anymore.但是当我在 GroupDocument 上调用.lean()时, _id丢失并且我无法再访问它。

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

It works if I would extend my Group from Documents like so:如果我像这样从 Documents 扩展我的组,它会起作用:

Group extends Document

But this isn't recommended by mongoose但这不是 mongoose 推荐的

I also thought about just putting the _id into the POJO like so:我还考虑过像这样将 _id 放入 POJO 中:

@Schema()
export class Group {

    _id: string;

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

But this seems to me not an ideal solution.但这在我看来不是一个理想的解决方案。

All I want to do is to make it possible to call group.id / group._id on a lean object. Is there any way to achieve that without harming any best practices?我想要做的就是在精益 object 上调用group.id / group._id成为可能。有没有什么方法可以在不损害任何最佳实践的情况下实现这一目标?

You have to define _id as:您必须将 _id 定义为:

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

To return just the '_id' field you could use project in database and just return the _id field要仅返回 '_id' 字段,您可以在数据库中使用项目并返回 _id 字段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM