Sunday, 7 May 2017

mongoose find by nested object ids return the entire document

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



via Gianluca Gini

No comments:

Post a Comment