Search code examples
node.jsmongodbmongoosesubdocument

Cant get specific subdoc and a 'root' value in the same call


I can get the specific sub document, but I want to have the email also

//The object in the Db looks like this:
{
    _id: some_id,
    email: "an email",
    order: [{
        fakturaId: faktura_id,
        name: "Some name"
        ...
     },...]
}

const salg = await mgUser.find(
    { _id: ObjectId('some_id')},
    {
        order: {
            $elemMatch: { fakturaId: faktura_id }
        }
    }
)

I get :

 {
        fakturaId: faktura_id,
        name: "Some name"
        ...
 }

And would like to have :

{
email : "an email",
     {
            fakturaId: faktura_id,
            name: "Some name"
            ...
     }
}

Or any kind where I get the email


Solution

  • Add email to the projection:

    const salg = await mgUser.find(
        { _id: ObjectId('some_id')},
        {
            email: 1,
            order: {
                $elemMatch: { fakturaId: faktura_id }
            }
        }
    )