【发布时间】:2020-12-17 19:43:16
【问题描述】:
我遇到了无法解决的 TypeScript 问题:
我正在使用 mongoose 架构的 post 函数在用户注册后立即为他/她生成一个配置文件(配置文件模型)(通过用户模型)。
我收到与 this 相关的类型 error。即使代码工作正常。所以我正在使用 ** // @ts-ignore **
接口:
interface UserAttrs {
firstName: string;
lastName: string;
email: string;
password: string;
}
interface UserDoc extends mongoose.Document {
firstName: string;
lastName: string;
email: string;
password: string;
}
// adding custom build function
interface UserModel extends mongoose.Model<UserDoc> {
build(attrs: UserAttrs): UserDoc;
}
更多代码:
// schema
const userSchema = new mongoose.Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true }
}, { // schema options
toJSON: {
transform(doc, ret) {
ret.id = ret._id;
delete ret._id;
delete ret.password;
delete ret.__v;
}
}
});
// generate profile for user
userSchema.post('save', async function () {
// @ts-ignore <---- TS ERROR
let firstName = this.get('firstName');
// @ts-ignore <---- TS ERROR
let lastName = this.get('lastName');
// @ts-ignore <---- TS ERROR
let user = this.get('id');
// @ts-ignore
const profile = new Profile({
firstName, lastName, user
})
await profile.save();
})
// configuring custom build function
userSchema.statics.build = (attrs: UserAttrs) => {
// builds a new user for us
return new User(attrs);
}
const User = mongoose.model<UserDoc, UserModel>('User', userSchema)
export { User }
非常感谢您的帮助,这让我发疯了。
【问题讨论】:
标签: node.js typescript express mongoose typescript-typings