【问题标题】:Property '_id' does not exist on type. Getting type error when trying to access property _id on result of a promise in nestjs application类型上不存在属性 \'_id\'。尝试在nestjs应用程序中访问promise结果的属性_id时出现类型错误
【发布时间】:2022-08-08 19:39:40
【问题描述】:

在我的嵌套应用程序中,在user 上调用_id 时出现类型错误,因为猫鼬自动定义了_id,因此它不存在于我定义为承诺类型的模式中。

当承诺类型更改为Promise<any> 之类的任何类型时,就不会出现类型错误。

async create(createUserDto: CreateUserDto): Promise<User> {
    const createdUser = await new this.userModel(createUserDto).save();
    return createdUser;
  }

但我想知道这是正确的方法还是我应该做其他事情。
我不想在架构中定义_id 来解决这个问题。

 @Prop({ auto: true})
 _id!: mongoose.Types.ObjectId;

用户架构.ts

// all the imports here....

export type UserDocument = User & Document;

@Schema({ timestamps: true })
export class User {

  @Prop({ required: true, unique: true, lowercase: true })
  email: string;

  @Prop()
  password: string;

}

export const UserSchema = SchemaFactory.createForClass(User);   

users.controller.ts

@Controller(\'users\')
@TransformUserResponse(UserResponseDto)
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Post()
  async create(@Body() createUserDto: CreateUserDto) {
      const user = await this.usersService.create(createUserDto);
      return user._id;
  }

}

users.service.ts

// all the imports here....  
   
@Injectable()
export class UsersService {
  constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {}

  async create(createUserDto: CreateUserDto): Promise<User> {
    const createdUser = await new this.userModel(createUserDto).save();
    return createdUser;
  }
}
  • 您可以使用Document.prototype.id 以字符串形式获取_id。换句话说,请改用user.id
  • 可以在模式中定义 _id,如果问题是为所有模式定义相同的属性,您可以定义一个基本模型并将该模型扩展到您的模型。
  • @JakeHolzinger user.id 也像我说的那样显示类型错误,因为在用户模式中 id 不存在。
  • 打字稿错误?如果您在 UserService 中返回 UserDocument,您应该可以访问该 ID。 User 类型没有 id 属性。
  • 你好我也面临这个问题。你解决了吗?怎么解决的?是否可以不手动定义 _id 属性?

标签: javascript typescript mongodb nestjs mongoose-schema


【解决方案1】:

您的create 服务方法应该返回Promise&lt;UserDocument&gt; 而不是Promise&lt;User&gt;UserDocument 具有指定的 _id 属性。

async create(createUserDto: CreateUserDto): Promise<UserDocument> {
    const createdUser = await new this.userModel(createUserDto).save();
    return createdUser;
  }

【讨论】:

    猜你喜欢
    • 2021-01-11
    • 2021-11-27
    • 2020-05-20
    • 2016-08-19
    • 2020-12-22
    • 2019-04-11
    • 2019-12-26
    • 2020-12-01
    • 2018-04-30
    相关资源
    最近更新 更多