Mongoose timestamps updatedAt access via code typescript

Viewed 319

When I call the database I get the document type returned.

const table: TableDocument = await this.tableSchema.create({ ...createTableDto })
console.log(table)

The table object looks like this:

{
  createdBy: '12',
  capacity: 4,
  tableNumber: 5,
  _id: new ObjectId("618bdb1ab2e5813b6f1fc198"),
  createdAt: 2021-11-10T14:45:46.279Z,
  updatedAt: 2021-11-10T14:45:46.279Z,
  __v: 0
}

but I am unable to access updatedAt via code.

table.__v exists

table.updatedAt does not exist on this type: TableDocument

If possible I would love to tell typescript I am returning a self defined type:

const table: ResponseTable = await this.tableSchema.create({ ...createTableDto })

Which does include updatedAt, but the error occurs: Table Document is not assignable to ResponseTable...

I am lacking to see how I work this out with mongoose 6.0 typescript support

1 Answers

So after a while I got this idea:

export type TableDocument = Table & Document & {updatedAt: Date, createdAt: Date}

When I create the TableDocument type after creating the Schema class Table, I just also add the updatedAt and createdAt property to it, so when mongoose tells me it is returning a TableDocument, the fields are included for Typescript to make use of them.

Related