【发布时间】:2019-06-14 10:54:26
【问题描述】:
我正在尝试在 Mongoose 中设置 toObject 方法的返回类型,尽管我不确定这是否可行。
使用泛型,可以设置 Document 对象的属性,该对象从使用 Mongoose 的查询返回,但这些对象的 getter 和 setter 通常在访问时运行许多验证代码,这是我想要的在某些情况下喜欢避免。
那些Document 对象具有返回等效匿名对象的toObject 方法,这就是我正在使用的,但那些返回的对象具有any 类型。我想在Schema 或Model 定义中设置这些对象的类型,这样我就不必在每次查询时都使用类型断言。
目前我的代码如下所示:
import mongoose, { Schema, Document } from 'mongoose'
interface User {
username: string,
email: string,
password: string,
}
const UserSchema = new Schema({
username: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
})
const UserModel = mongoose.model<User & Document>('User', UserSchema)
export { User, UserModel }
有了这个,我可以使用以下代码执行查询:
const userDocument = await UserModel.findById(id)
const userObj = userDocument && userDocument.toObject()
虽然userDocument 属于User extends Document 类型,但userObj 属于any 类型。我想将其设置为 User 类型。
【问题讨论】:
标签: typescript mongoose