This is my document structure:
{
"_id": "590dc8b17e52f139648b9b94",
"parent": [
{
"_id": "590dc8b17e52f139648b9b95",
"child": [
{
"_id": "590dc8b17e52f139648b9b8f"
},
{
"_id": "590dc8b17e52f139648b9b90"
}
]
},
{
"_id": "590dc8c57e52f139648b9b9b",
"child": [
{
"_id": "590dc8c57e52f139648b9b96"
}
]
}
]}
I'm trying to return only the information about the nested object which i'm looking for with its _id.
router.get('/child/:id', (req, res) => {
Project.findOne({ 'parent.child._id': req.params.id },
(err, results) => {
if (err)
res.status(500).send(err);
res.status(200).json(results.parent[0].child.id(req.params.id));
}
)});
the problem is that results contains the entire document which may contain multiple instances of parent So obviously my code only works if the known child _id it's in the first parent.
How can i fix it? many thanks
so apparently the unwind and match solution is good but for mongoose you need to explicitly say that the id is an ObjectId type.
{$match:
{ "parent.child._id": new mongoose.Types.ObjectId(id) }
}