mongoose get items from subdocument code example

Example 1: mongoose update subdocument by id

//this method for add data to subdocument
BlogPost.findById(req.params.postId, function (err, post) {
    var subDoc = post.comments.id(req.params.commentId);
    subDoc = req.body;
    post.save(function (err) {
        if (err) return res.status(500).send(err);
        res.send(post);
    });
});

// alternative second method you can use this
BlogPost.findOneAndUpdate({_id: req.params.postId}, {$push:{ subDoc: req.body }}, (err, doc) => {
  	// do something here
});

Example 2: populate subdocument mongoose

ProjectMetadata.findOne({id:req.params.prjId})
    .populate(
        [{
        path:'tasks',
        model:TaskMetadata,
        populate:[{
            path:'assigned_to',
            model:User,
            select:'name employee_id'
        },
        {
            path:'priority',
            model:Priority,
            select:'id title'
        }],
        select:"task_name id code assign_to stage priority_id"
    },
    {
        path:'client',
        model:Client,
        select:"client_name"
    },
    {
        path:'prjct_mgr',
        model:User,
        select:"name"
    },
    {
        path:'acc_exec',
        model:User,
        select:'name employee_id'
    },
    {
        path:'poc',
        model:User,
        select:'name employee_id'
    },
    {
        path:'prj_type',
        model:ProjectType,
        select:"type -_id"
    }

])