mongoose looking for a better way to get documents

Issue

This Content is from Stack Overflow. Question asked by Mehdi M

consider there are 3 collections :

Company : {
    name
}

Department: {
    name,
    company_id
}

Person: {
    name,
    department_id
}

and we want to get all persons in a company, by company name.

i know the way to first get the company id in one query, and then get the list of department_ids in another query, and then get the list of persons, in another query with the list of Ids :

    async function query(){
        let companyId = await Company.findOne({name}).distinct('_id').exec();
        let departmentIds = await Department.find({company_id : companyId } ).distinct('_id').exec();
        let persons = await Person.find({department_id : departmentIds}).exec();
    }

I want to know is there any better way to do this, I mean is it possible to use populate method or aggregation here? and if yes how?
thanks in advance.



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?