Javier Bandomo Ruiz
Javier Bandomo Ruiz

Reputation: 33

How to use mongoose to return field from object array in string array

I have a query in mongoose that return this:

{
    some_keys: "some values", 
    objs:[
        {name:"name1"}, 
        {name:"name2"} 
    ] 
}

I want to return in this format:

{ 
    some_keys: "some values",
    objs:[
        "name1", 
        "name2" 
    ] 
}

Upvotes: 3

Views: 53

Answers (1)

Dheemanth Bhat
Dheemanth Bhat

Reputation: 4452

Using $map operator loop through the objs array and return only the value of the name filed for every obj.

Try this:

const result = await testSchema.aggregate([
    {
        $addFields: {
            objs: {
                $map: {
                    input: "$objs",
                    as: "obj",
                    in: "$$obj.name"
                }
            }
        }
    }
]);

Output

{
    "_id" : ObjectId("..."),
    "some_keys" : "some values",
    "objs" : [
        "name1",
        "name2"
    ]
}

Upvotes: 1

Related Questions