这是我第一次使用typescript和mongoose。这是我所做的代码。
类型
export interface User extends Document {
_id: ObjectId;
lastName: string;
}
架构
const userSchema = new Schema<User>({
lastName: { type: String, required: true, trim: true },
});
型号
const User = model<User>('user', UserSchema, 'users');
请求
const user = await User.findById(userId).exec();
我希望user
变量的类型是User | null
,但我得到的是(User & {_id: Schema.Types.ObjectId;}) | null
。我做错了什么我该怎么解决?
我希望
user
变量的类型为User | null
好吧,这只是一个无效的期望。
在源代码中,Model<User>.findById(…).exec()
调用被显式键入以返回:
Promise<HydratedDocument<User, {}, {}> | null>
…最终解决为:
Promise<(User & { _id: ObjectId }) | null>
不管怎样,& { _id: ObjectId }
部分总是被添加的,除了接受这种类型(这应该不会有太大问题(之外,你似乎对此无能为力。
参考文献:
Model.findById()
的定义:https://github.com/Automattic/mongoose/blob/master/index.d.ts#L856Query.exec()
的定义:https://github.com/Automattic/mongoose/blob/master/index.d.ts#L2096HydratedDocument<…>
的定义:https://github.com/Automattic/mongoose/blob/master/index.d.ts#L737Require_id<…>
的定义(内部(:https://github.com/Automattic/mongoose/blob/master/index.d.ts#L735