Nest Js,如何在架构中正确设置 _id 属性

uni*_*ise 1 mongoose node.js nestjs

我知道这看起来很基本,但我似乎找不到在 Nest.js 猫鼬模式中设置 _id 字段的正确方法。我附上了一张图片,只是想知道设置此属性的最佳方法是什么?我收到以下错误

“SchemaType”仅指类型,但在此处用作命名空间。ts(2702)

在此输入图像描述

Dez*_*ley 5

您不需要定义_id为 prop,因为它已经存在于Document类中。违背您意愿执行的查询MusicSupervisorModel将返回 的对象MusicSupervisorDocument。如果您想将类型字段添加ObjectId到架构中,您必须按如下方式进行操作以保留转换为ObjectId

import { Document, SchemaTypes, Types } from 'mongoose';

...

@Prop({ type: SchemaTypes.ObjectId })
yourField: Types.ObjectId
Run Code Online (Sandbox Code Playgroud)

  • 当您想要接收模型实例然后访问该实例上的 _id 时,您应该设置什么参数类型...如果我只键入一个参数,因为模型类 _id 未在架构上定义并且打字稿有问题例如: User Model: `@Schema() export class User { @Prop() name?: string; }` 某些服务: `async someActoin(user: User) { // 错误:类型 'User'.ts(2339) 上不存在属性 '_id' }` (3认同)