简体   繁体   English

Mongoose 查询返回多个结果

[英]Mongoose query returning more than one result

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'因此,如果 work_email 是test@test.com ,则应返回的公司名称应为'a name'

So the query i built with mongoose is this:所以我用 mongoose 构建的查询是这样的:

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.但这将返回所有公司名称(从条目一开始),而不是我正在寻找的单一名称。

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蒙戈游乐场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM