在mongoose 6和typegoose 10中将ObjectId转换为String

xkrw2x1b  于 2023-04-30  发布在  Go
关注(0)|答案(1)|浏览(174)

我从 Mongoose 5跳到6,甚至到7。
但是我不能再Map我的user_id属性了,因为这个TypeError: Function.prototype.toString requires that 'this' be a Function

import type { DocumentType } from '@typegoose/typegoose'
import { getModelForClass, prop } from '@typegoose/typegoose'

export class ExperimentUser {
  @prop({})
  public user_id?: mongoose.Types.ObjectId
}

export type ExperimentUserDocument = DocumentType<ExperimentUserSchema>
export const ExperimentUserModel = getModelForClass(ExperimentUser)
import { HydratedDocument } from 'mongoose'

private map(document: HydratedDocument<ExperimentUser>): ExperimentUserDTO {
    return {
      id: document._id.toString(),
      user_id: document.user_id?.toString()
//                              ^
//TypeError: Function.prototype.toString requires that 'this' be a Function

    }
}
import mongoose from 'mongoose'

async create(user_id?: string): Promise<ExperimentUserDTO> {
    const created_user = await ExperimentUserModel.create({
      user_id: user_id ? new mongoose.Types.ObjectId(user_id) : undefined
    })
    return map(created_user)
  }

任何帮助将不胜感激
干杯

5rgfhyps

5rgfhyps1#

答案在typegoose文档中:)https://typegoose.github.io/typegoose/docs/guides/advanced/using-objectid-type/
由于将其定义为类型ObjectId = mongoose,因此需要引用完整长度类型。ObjectId和引用,这将导致它在编译时成为Object,这意味着Typegoose将把属性类型转换为Mixed。
在我的代码库中,我有一个别名,我缩短了示例的ObjectId,并在我的类定义中使用它。这是导致问题的原因。

type ObjectId = mongoose.Types.ObjectId
export class ExperimentUser {
  @prop({})
  public user_id?: ObjectId
}

干杯!

相关问题