question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

TypeScript: timestamps not inferred from schema

See original GitHub issue

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

6.4.0

Node.js version

18.2.0

MongoDB server version

5.0.9

Description

Hi there, my issue is to do with typescript.

The issue I am having is that when creating a document schema with timestamps enabled the inferred document type doesn’t have the corresponding createdAt and updatedAt fields present.

This means that when querying documents through the schema typescript will throw the property doesn’t exist on type issue for the createdAt and updatedAt fields.

Hope this is pretty simple to understand, I’ve done my best to proved a good code example to best explain the issue I am having.

I realised mongoose has just recently migrated to typescript and isn’t fully feature complete yet so appreciate any help.

P.s. I realise I haven’t manually typed the interface for the schema e.g. new Schema<IDocument> and export const Document = model<IDocument>('Document', DocumentSchema); this is because we are migrating our whole code base to typescript and would ideally like to save some time by using InferSchemaType. But obviously open to any ideas even if it’ll end up requiring typing the interfaces manually.

Thanks.

Steps to Reproduce

import { Schema, model, Model, InferSchemaType } from 'mongoose';

const DocumentSchema = new Schema(
  {
    url: { type: String, required: true, unique: true },
    fileSize: { type: Number, required: true },
    mimeType: { type: String, required: true },
    fileName: { type: String, required: true },
  },
  {
    timestamps: true,
  }
);

// Document comes out as
// const Document: Model<{
//   url: string;
//   fileSize: number;
//   mimeType: string;
//   fileName: string;
// }, {}, {}, {}, any>
export const Document: Model<InferSchemaType<typeof DocumentSchema>> = model(
  'Document',
  DocumentSchema
);

async function findDocument(id: string) {
  // Document without timestamp in query
  const doc1 = await Document.findById(id);
  if (doc1) {
    console.log(doc1.createdAt); // Error: "Property 'createdAt' does not exist on type 'Document...'"
    console.log(doc1.updatedAt);// Error: "Property 'updatedAt' does not exist on type 'Document...'"
  }

  // With timestamp in query
  const doc2 = await Document.findById(id, undefined, { timestamps: true });
  if (doc2) {
    console.log(doc2.createdAt); // Error: "Property 'createdAt' does not exist on type 'Document...'"
    console.log(doc2.updatedAt); // Error: "Property 'updatedAt' does not exist on type 'Document...'"
  }
}

Expected Behavior

Expect the Document to have the timestamp fields present on the returned type.

Issue Analytics

  • State:closed
  • Created a year ago
  • Reactions:12
  • Comments:8 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
Adizbekcommented, Oct 15, 2022

@janickvwcotiss @neocameback For quick fix, you can try to use SchemaTimestampsConfig image

1reaction
neocamebackcommented, Oct 3, 2022

Could you try to access with following post['createdAt'] instead of post.createdAt

Read more comments on GitHub >

github_iconTop Results From Across the Web

Mongoose - can't access createdAt
I'm creating a NestJs application using Mongoose, I'm currently having a problem trying to access createdAt even though I have set timestamps to ......
Read more >
Schemas in TypeScript
Mongoose schemas are how you tell Mongoose what your documents look like. Mongoose schemas are separate from TypeScript interfaces, so you need to...
Read more >
Using with TypeScript
Note that it's currently not possible for JTDDataType to know whether the compiler is inferring timestamps as strings or Dates, and so it...
Read more >
@modelOptions | typegoose
ALLOW : allow the use and execution of mongoose.Schema.Types.Mixed , if the inferred type cannot be set otherwise · WARN : [default] Warn...
Read more >
sanity-typed-schema-builder
Typescript types for Sanity Values! ALL types are inferred! No messing with generics, awkward casting, or code generation. Zod schemas for parsing ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found