Reputation: 721
I have a model:
const schema = new mongoose.Schema({
country: { type: String },
code: { type: String },
region: [{
name: { type: String },
city: [{
name: { type: String },
latitude: { type: String },
longitude: { type: String },
}],
}],
})
I need to get list of region -> city -> name (list of sities names) In the begining I tried a query to get list of (Array)city
const list = await Model.findOne(
{ $and: [{ code: req.params.code }, { 'region.name': 'Harjumaa' }] },
{ 'region.city.name': 1 },
)
And receive this data:
Then I search list of regions I send query:
Model.findOne({ code: req.params.code }, { region: 1 })
And receive data like this:
I want to get list of cities names in the same format.
My data sample:
{
"country": "Estonia",
"code": "ee",
"region": [
{
"name": "Harjumaa",
"city": [
{
"name": "Aegviidu vald",
"latitude": "59.27941132",
"longitude": "25.62571907"
},
{
"name": "Anija vald",
"latitude": "59.27643967",
"longitude": "25.48167992"
}
]
}
]
}
Upvotes: 1
Views: 67
Reputation: 49945
$project
with $region.city.name
path will give you an array of arrays since you have two levels of nesting. To fix that you can use $reduce with $concatArrays which will flatten your final result into single array, try:
Model.aggregate([
{
$match: { code: "ee" }
},
{
$project: {
cityNames: {
$reduce: {
input: "$region.city.name",
initialValue: [],
in: { $concatArrays: [ "$$this", "$$value" ] }
}
}
}
}
])
Upvotes: 1