Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

287
Views
Mongoose + NestJS: Populated nested virtuals don't get returned

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

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!