Typescript & mongo models



基本上我在我的存储库中使用了这个方法:

async findByEmail(email: string): Promise<User | null> {
const user = await UserModel.findOne({
email
});
if(!user) return null;
const obj = user.toObject();

obj.id // error property 'id' does not exist on type
}

我有两个模型,一个mongo模型和一个正常模型(类型),这是mongo模型,我创建了一个虚拟机,用id代替_id:

const schema = new mongoose.Schema({
email: {type: String, required: true, unique: true},
password: String
}, {
toJSON: {
virtuals: true,
transform: function (doc, ret, options) {
ret.id = ret._id;
delete ret.__v;
delete ret._id;
}
},
toObject: {
virtuals: true,
transform: function (doc, ret, options) {
ret.id = ret._id;
delete ret.__v;
delete ret._id;
}
}
});
export const User = mongoose.model('user', schema);

这是域模型:

export type User = {
id: string,
email: string,
password: string
}

我一直在findByEmail函数上得到property 'id' does not exist on type错误,任何想法(我不想创建一个扩展猫鼬的UserDocument接口)。文档,因为我试图使用干净的架构,我认为模型不应该意识到数据库的东西)

我通过输入模式&模型如:

const schema = new mongoose.Schema<User>({});
const UserModel = mongoose.model<User>('user', schema);

相关内容

  • 没有找到相关文章

最新更新