manoj
manoj

Reputation: 5643

Return Array from Embedded document

I have a data like in mongodb collection name property.

{
            "_id": "593a3d828e2ef100d1496e77",
            "feature_type": "house",
            "features": [
                {
                    "name": "h1"
                },
                {
                    "name": "h2"
                }
            ]
        }

I want only

 [
            {
                "name": "h1"
            },
            {
                "name": "h2"
            }
        ]

as result i tried this by

req.db.collection('FeatureSettings').findOne({feature_type: req.params.feature_type}, {features: 1});

this give

{
    "_id": "593a3d828e2ef100d1496e77",
    "features": [
        {
            "name": "Hotel"
        },
        {
            "name": "Apartment"
        }
    ]
}

what can i do to get result as given above.

Upvotes: 0

Views: 46

Answers (3)

Shaishab Roy
Shaishab Roy

Reputation: 16805

You can try this to return only features array values.

req.db.collection('FeatureSettings')
 .findOne({feature_type: req.params.feature_type}, {features:1, _id:0}).features;

OR

// if you use mongoose can use 
return req.db.collection('FeatureSettings')
  .findOne({feature_type: req.params.feature_type}, {features:1, _id:0})
  .exec()
  .then((result) => {
     return result.features;
  });

Upvotes: 0

7hibault
7hibault

Reputation: 2459

Assuming you're using something like mongoose that returns promises, you could use the result of the query

return req.db.collection('FeatureSettings')
.findOne({feature_type: req.params.feature_type}, {features: 1})
.then((result) => {
    return result.features;
});

Upvotes: 0

oggo
oggo

Reputation: 117

You have to exclude the _id from your projection like here:

req.db.collection('FeatureSettings').findOne({feature_type: req.params.feature_type}, {features: 1, _id:0});

Upvotes: 0

Related Questions