在打字稿中用猫鼬填充查询 [英] Populate a query with mongoose in typescript
问题描述
我在用打字稿填充用户模型时遇到麻烦.我具有用户方案的属性,该属性是对其个人资料的引用.为了用打字稿实现猫鼬,除了架构之外,我还必须定义一个tpo/接口.我的问题是我不知道必须将什么类型分配给配置文件属性.因为如果我在不填充查询的情况下运行查询,它将是一个"ObjectId",但是如果填充它,它将包含整个配置文件.
I'm having trouble populating my user model with typescript. I have a property of the user's scheme which is the reference to his profile. To implement mongoose with typescript I had to define a tpo / interface in addition to the schema. My problem is that I do not know what type I have to assign to the profile property. Because if I run the query without populating it, it will be an "ObjectId", but if I populate it will contain the whole profile document.
export type UserModel = mongoose.Document & {
name: string;
username: string;
email: string;
password: string;
profile: Schema.Types.ObjectId; // If I leave this property with this type, in case I populate a typescript query it would give me an error.
};
export const UserSchema = new Schema({
name: {
type: String,
required: true
},
username: {
type: String,
required: true,
unique: true
},
email: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
profile: {
type: Schema.Types.ObjectId,
ref: "Profile"
}
});
export default model<UserModel>("User", UserSchema);
推荐答案
我的问题是我不知道必须将哪种类型分配给 个人资料属性.
My problem is that I do not know what type I have to assign to the profile property.
您将需要定义2种类型/接口.
You are going to need to define 2 types/interfaces.
export default model<UserModel>("User", UserSchema);
此导出操作必须使用其他界面,在该界面中您已填充个人资料"文档.
This export will have to use a different interface in which you have the populated "Profile" document.
对于架构本身,您可以将其保留为objectID类型.
For the schema itself you can leave it as an objectID type.
这篇关于在打字稿中用猫鼬填充查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!