Search code examples
node.jsmongoosesubdocument

Mongoose - query to get all subdocuments of a document


I'm quite new with mongoose, I have a list of companies and each company has a subarray of users. I just want to retrieve with mongoose all users of a specific company:

a single company is like

{
    "_id": "57ffa47f5b70f90831212348",
    "name": "mycompany",
    "address": "...",
    "phone": "...",
    "users": [
        {
            "_id": "57ffa47f5b70f90831212347",
            "username": "alpha",
            "name": "myname",
            "surname": "mysurname",
            "password": "..."
        }
    ]
}

I tried with

Company.findOne({
        'name': req.user.name
    })

      .aggregate({$unwind: '$users'})

      .exec(
        function(err, users) {
          if (err) res.status(500).send(err);

          res.json(users);
        });

but I had no luck... I'm not sure how to use aggregate correctly.


Solution

  • Just populate company.users

    Company.findOne({
            'name': req.user.name
        })
          .populate('users', 'username name surname')
          .exec(
            function(err, company) {
              if (err) res.status(500).send(err);
    
              res.json(company.users);
            });