Converting ObjectId to String in mongoose 6 and typegoose 10

366 views Asked by At

I'm jumping from mongoose 5 to 6, and even to 7.

But I can't map my user_id property anymore because this 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)
  }

Any help will be much appreciated

Cheers

1

There are 1 answers

0
Nainpo On

Well the answer is in typegoose documentation :) https://typegoose.github.io/typegoose/docs/guides/advanced/using-objectid-type/

You need to refer to the full length type since defining it as type ObjectId = mongoose.Types.ObjectId and referencing that will lead to it being an Object at compile time, meaning Typegoose will translate the property type to Mixed.

In my codebase, I had an alias that I shortened for the example, for ObjectId, and was using it in my class definition. This was causing the issue.

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

Cheers !