Reputation: 566
How can I get an array of property values without the object structure. Here is my schema
_id: {
type: Schema.Types.ObjectId,
ref: "User"
},
services: [{
_id:false,
service_category: {
type: Schema.Types.ObjectId,
ref: "ServiceCategory"
},
sub_services :[{
_id:false,
service : {
type: Schema.Types.ObjectId,
ref: "Service"
}
}]
}]
And this is how I was going to query the results
Vendor.find({ '_id': req.user._id, 'services.service_category':req.body.category_id},'services.sub_services.service').exec(function (err, rtnobj) {
if (err) {
console.log(err);
return (err);
}
else{
res.send(rtnobj);
}
})
But it gives me this output
[
{
"_id": "598b28271a0b551af8fbf849",
"services": [
{
"sub_services": [
{
"service": "service 1 _id"
},
{
"service": "service 2 _id"
}
]
}
]
}
]
But I need the result in following format
[ "service 1 _id", "service 2 _id",......]
Is there any standard approaches to do this. Or any alternative methods
Thanks
Upvotes: 3
Views: 2271
Reputation: 22553
If you want to use a query, then you might as well just keep doing what you do now and then to map over the results:
Vendor.find({ '_id': req.user._id, 'services.service_category':req.body.category_id},'services.sub_services.service').exec(function (err, rtnobj) {
res.send(rtnobj.services.sub_services.map(each => each.service))
})
You could also use the aggregation framework to do something similar. but I think the above would be most idiomatic.
Upvotes: 1