Johne Doe
Johne Doe

Reputation: 452

$AddFields adding Array instead of Single Value

I am using following code where soft_id field is being added based on the software value in the purchased object, but unfortunately, its adding an array by taking ids of all existing softwares.

const user = await User.aggregate()
        .match({ _id: ObjectId(id) })                       
        .addFields({                
            'purchased.soft_id': '$purchased.software'
        })

    res.send(user);

This is the output which I am getting after using above code.

{
    "_id": "5f6f71685c370b1bec3763fc",
    "role": "user",
    "email": "[email protected]",
    "password": "test123",
    "purchased": [
        {
            "software": "5f6e47eb92d318037c0a6e50",
            "expiredAt": "1970-01-19T12:32:40.241Z",
            "soft_id": [
                "5f6e47eb92d318037c0a6e50",
                "5f5d410d61fea800f01d8714",
                "5f6f804490b35a0398c64cd5"
            ]
        },
        {
            "software": "5f5d410d61fea800f01d8714",
            "expiredAt": "1970-01-19T12:32:40.241Z",
            "soft_id": [
                "5f6e47eb92d318037c0a6e50",
                "5f5d410d61fea800f01d8714",
                "5f6f804490b35a0398c64cd5"
            ]
        },
        {
            "software": "5f6f804490b35a0398c64cd5",
            "expiredAt": "1970-01-19T12:32:40.241Z",
            "soft_id": [
                "5f6e47eb92d318037c0a6e50",
                "5f5d410d61fea800f01d8714",
                "5f6f804490b35a0398c64cd5"
            ]
        }
    ],
    "createdAt": "2020-09-26T16:50:48.872Z",
    "updatedAt": "2020-09-26T17:54:19.208Z",
    "__v": 0
}
]

Upvotes: 1

Views: 884

Answers (1)

turivishal
turivishal

Reputation: 36104

It can not access direct array of object elements, you need to use some array operators, like $map,

  • $map to iterate loop, and add new field soft_id with value of software and merge objects using $mergeObjects,
const user = await User.aggregate()
    .match({ _id: ObjectId(id) })                       
    .addFields({                
        purchased: {
            $map: {
                input: "$purchased",
                in: {
                    $mergeObjects: [
                        "$$this",
                        { soft_id: "$$this.software" }
                    ]
                }
            }
        }
    });

    res.send(user);

Playground

Upvotes: 1

Related Questions