【发布时间】:2021-11-24 06:07:30
【问题描述】:
我的架构是这样的
Schema()
export class User {
@Prop({ required: true })
name: string;
@Prop({ required: true })
email: string;
@Prop({ type: mongoose.Types.ObjectId, ref: 'Course' })
courses: Course[];
}
@Schema()
export class Course {
@Prop()
name: string;
@Prop([{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }])
participants: User[];
@Prop([{ type: mongoose.Schema.Types.ObjectId, ref: 'Lesson' }])
lessons: Lesson[];
}
我想要实现的是获得特定用户注册的一系列课程。我尝试这样做的方式是这样的。
async findUserCoursesByUserEmail(email) {
const user = await this.userModel
.findOne({ email })
.populate('courses')
.exec();
return user.courses;
}
但作为回应,我得到了一个像这样的对象,但它应该是一个数组。
{
"lessons": [],
"participants": [
"6157a5ba06afba420464fb65"
],
"_id": "6157a5ac06afba420464fb61",
"name": "Matematyka Rozszrzona",
"__v": 1
}
用户对象如下所示。
{
"_id": "6157a5ba06afba420464fb65",
"name": "Jacob",
"email": "test@test.pl",
"courses": [
"6157a5ac06afba420464fb61",
"6158d64891be3f50f85bef0a"
],
"__v": 2
}
任何帮助都将不胜感激,因为我在这个问题上卡了很长时间。
【问题讨论】:
标签: mongodb mongoose nestjs mongoose-populate