Is there a way to retrieve the first item from a nested Array without having to fetch the entire document?
Data Schema/Model
Consider the following Schema:
const parentSchema = mongoose.Schema({
name: String,
children: []
});
const grandparentSchema = mongoose.Schema({
name: String,
children: [parentSchema]
})
This schema translates into the example instance shown below:
{
name: 'Grandparent Foo',
children: [
{
name: 'Parent Foo',
children: ['Child Foo', 'Child Bar', 'Child Baz']
}
]
}
The Query
I am trying to access the first child of 'Parent Foo'
. Essentially, I want to retrieve 'Child Foo'
.
Important Details
In this scenario, the grandchildren are stored as plain strings and not as separate documents (unlike the Parent), making it impossible to select them using dot notation.
I do not wish to fetch the entire document and filter through it in my code. My goal is to only transmit the first grandchild over the network as the
children
array of'Parent Foo'
might contain an immense number of entries.The reason behind this query is that I intend to use
$pop
method on the first grandchild after fetching it. Therefore, I need to fetch the item first and then perform the$pop
operation on it.