Description
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.