【发布时间】:2021-10-30 13:57:50
【问题描述】:
这是我的模型,紧跟 the docs for mongoose v5.13.x with TypeScript:
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);
好的,现在我想要创建和检索模型的函数。当我创建它时,自动创建的字段如_id、archived、created_at 和updated_at 都应该是可选的。但是当我检索它时,它们应该都可用。例如:
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);
};
但是,这会左右抛出类型错误;它会说_id 在Foo.create() 的输出中是可选的,如果我将它添加到我的类型中,Foo.create(foo) 会感到不安。
在这种情况下,键入_id、created_at 等字段的正确方法是什么?
【问题讨论】:
标签: typescript mongodb express mongoose