Итак, у меня есть эта модель проекта, у которой есть владелец, который может быть либо пользователем, либо командой.
const projectSchema = new Schema<IProject>({
projectName: {
type: String,
required: true
},
description: {
type: String,
required: false
},
site: {
type: String,
required: false
},
owner: {
type: Schema.Types.ObjectId,
required: true,
refPath: 'ownerModel'
},
ownerModel: {
type: String,
required: true,
enum: ['Team', 'User']
},
slug: {
type: String,
required: true,
unique: true,
dropDups: true
},
keywords: {
type: [String],
required: true
}
})
Проблема, с которой я сталкиваюсь, заключается в том, что владельцем является команда, потому что у команд может быть несколько владельцев, например
const teamSchema = new Schema<ITeam>({
teamName: {
type: String,
required: true
},
owner: {
type: [Schema.Types.ObjectId],
required: true,
ref: 'User'
},
slug: {
type: String,
required: true,
unique: true
},
bio: {
type: String,
required: false
},
verified: {
type: Boolean,
required: true,
default: false
},
quote: {
type: String,
required:false
},
members: [{
member: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
status: {
type: String,
required: true,
enum: ["accepted", "pending"]
},
type: {
type: String,
required: true,
enum: ["admin", "coworker"]
}
}],
followers: {
type: Number,
required: true
},
logo: {
type: String,
required: false
},
type: {
type: String,
required: true
},
})
И хотя мне нужно заполнить поле владельца проекта (также известное как загрузка команды), я не могу на всю жизнь заставить ни владельца команды, ни ее участников загружать через заполнение.
Я попробовал owner.owner, попытался изменить модель, чтобы не использовать массив, попытался использовать плагин deepPopulate, но получил ошибку типа. Ничего не получилось
Я обнаружил, как это сделать. Все, что мне нужно было сделать, это правильно использовать объект Mongoose. Я не знаю, как я позволил этому пройти мимо меня.
Вот:
let projetos = await ProjectModel.find({owner: args.id, ownerModel: "Team"})
.populate({ path: 'owner',
populate: [
{
path: 'owner'
},
{
path: 'members'
}
]
});
Я использовал массив, так как хотел заполнить более одного поля. Документ Mongoose об этом