I have the following MongoSchema with some nested virtuals that I'd like to populate:
// activity.schema.ts
interface IGlobalUser {
name: string
}
interface IUser {
globalUserId: Types.ObjectId
globalUser?: IGlobalUser // virtual
}
interface IWorker {
userId: Types.ObjectId
userObj?: IUser // virtual
}
@Schema({ toObject: { virtuals: true }, toJSON: { virtuals: true } })
export class Activity extends Document {
@Prop()
workers: IWorker[]
}
const ActivitySchema = SchemaFactory.createForClass(Activity)
ActivitySchema.virtual('workers.userObj', {
ref: 'Users',
foreignField: '_id',
localField: 'workers.userId',
justOne: true
})
ActivitySchema.virtual('workers.userObj.globalUser', {
ref: 'GlobalUsers',
foreignField: '_id',
localField: 'globalUserId',
justOne: true,
})
Let's get the activities:
// activity.service.ts
@Injectable()
export class {
constructor(
@InjectModel(Activity.name)
private readonly activityModel: Model<Activity>,
) {}
async getActivities() {
const activities = await this.activityModel
.find({})
.populate({
path: 'workers.userObj',
populate: {
path: 'globalUser
}
})
// console.log(activities[0].workers[0].userObj?.globalUser) <-- works fine, it's populated
return activities // This is then just passed to NestJS controller and returned to FE)
}
}
When I populate the nested workers.userObj.globalUser, it seems to work fine. (globalUser is populated, at least console.log(activities.workers[0].userObj?.globalUser) tells me so...)
BUT once the result is sent back to frontend, the workers.userObj.globalUser is missing while workers.userObj is still there.
How do I make sure it doesn't get lost?
Just a note: using @nestjs/mongoose@9.0.2 and mongoose@6.1.6