Following the guidelines from the official documentation for implementing mongoose v5.13.x with TypeScript, I have developed my model as shown below:
import mongoose, { Model, Schema, Types } from "mongoose";
export interface Foo {
label: string;
archived: boolean;
created_at: number;
updated_at: number;
}
const FooSchema = new Schema<Foo, Model<Foo>, Foo>(
{
label: { type: String },
archived: { type: Boolean, default: false },
},
{
timestamps: {
createdAt: "created_at",
updatedAt: "updated_at",
currentTime: () => Date.now() / 1000,
},
}
);
const Foo: Model<Foo> = mongoose.model<Foo>("Foo", FooSchema);
Now, my goal is to implement functions that can create and retrieve instances of this model. When creating a new instance, certain fields like _id
, archived
, created_at
, and updated_at
should be optional. However, when retrieving an existing instance, all these fields should be accessible. Here's an example:
type FooInput = {
label: string;
};
type FooOutput = {
_id: string;
label: string;
archived: boolean;
created_at: number;
updated_at: number;
};
export const createFoo = async (foo: FooInput): Promise<FooOutput> => {
return await Foo.create(foo);
};
Unfortunately, I am encountering type errors while trying to implement this approach; the output of Foo.create()
claims that _id
is optional, leading to conflicts when specifying types. How can I correctly define the fields such as _id
, created_at
, etc in this scenario?