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

155
Views
How can I filter by nested data in mongoose?

I have a User entity that has a role prop:

@Prop({ type: Types.ObjectId, ref: 'Roles' })
  role: Role | Types.ObjectId;

Role type:

export interface Role {
  _id: Types.ObjectId;
  name: string;
  permissions: Permission[] | Types.ObjectId[];
}

Query to get users:

async getUsers(body: EntitiesGetDto): Promise<User[]> {
    return this.usersModel
      .find(body.filter)
      .skip(body.offset)
      .limit(body.limit)
      .populate('role')
      .sort(body.sort ?? {});
  }

How can I get users filtered by role? (by role._id or role.name)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If you are using 2 different Models and schemas try using aggregate lookup, instead of using populate. Replace the query fields to match your use case:

// initiate the aggregate func
const aggr = this.userModel.aggregate();
// filter by user fields
aggr.match(body.filter);
// add lookup to match with the roles schema
aggr.append(
    [{ $lookup: {
        from: "role",
        localField: "user_role",
        foreignField: "user_role",
        as: "roles"
      }
    },
    // match the requested fields 
    { $match: { '$roles.name': "..some name.." } },
    // return the relevant data from the Model
    { $project: {
        _id: 1,
        role_name: '$roles.name',
        user_field3: 1,
        user_field4: 1,
      }
    }
  ]);
about 4 years ago · Juan Pablo Isaza Report
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!