Mongoose query returning more than one result

Viewed 114

My database structure is looking like this :

    {
        'name' : 'entry one'
        'project' : 
            [
                {companyName : 'a name', contactPerson : [{ work_email: 'test@test.com'}] } , 
                {companyName : 'a name1', contactPerson : [{ work_email: 'test1@test.com'}] } , 
                {companyName : 'a name2', contactPerson : [{ work_email: 'test2@test.com'}] } 
            ]
    }



    {
        'name' : 'entry 2'
        'project' : 
            [
                {companyName : 'another name', contactPerson : [{ work_email: 'testing@test.com'}] } , 
                {companyName : 'another name1', contactPerson : [{ work_email: 'testing1@test.com'}] } , 
                {companyName : 'another name 2', contactPerson : [{ work_email: 'testing2@test.com'}] } 
            ]
    }

What i want is to find the companyName that belongs to a given work_email. So if the work_email is test@test.com the company name that should be returned should be 'a name'

So the query i built with mongoose is this :

const projects = await ClientManagers.findOne({'project.contactPerson.work_email' : 'test@test.nl'} , 'project.companyName'); 

But this is returning all company names (from entry one) not the single one i am looking for.

1 Answers

Filtering will always return whole document. You need to use projection to "reshape" it. You can consider the $ (projection) operator:

const projects = await ClientManagers.findOne({'project.contactPerson.work_email' : 'test@test.nl'} , { 'project.$': 1 }); 

Mongo Playground

Related