Search code examples
mongoosemongoose-populate

Unable to populate user with subdocument polls


I have two models User and Poll. In my routes I have a param that gets the :userId from the route and gets the user to return.

Currently returns

{
    "_id": "599db6cff368b504ea355781",
    "hash": "3010661bdf06e640f12d99c1b0549ac4a36f785a25dd02ed51d1f67dc9fb7048d3869a3d906aeb64825879c0dcded91f13feed5408687866e194439fa15a50a8",
    "salt": "9b53655d0a2c65b1b6ab499c76f91f3e",
    "email": "[email protected]",
    "username": "rawlejuglal",
    "__v": 3,
    "pollsVoted": [],
    "pollsCreated": [
        "599db6d9f368b504ea355782",
        "599db6e7f368b504ea355783",
        "599db6f4f368b504ea355784"
    ]
}

I'd like it to populate the user.pollsCreated with the Poll data and not just the ids. I've tried to follow the http://mongoosejs.com/docs/populate.html but I'm not sure if it is different with query instead of model.find. The link is to gist of relevant files. https://gist.github.com/RawleJuglal/db3bad809edfbfdd7d4da4edaebc5bd3


Solution

  • I'm going to post the solution I found. My gist did have a typo in the User model referencing 'Post' instead of 'Poll' but I'm leaving the code to correctly use populate if you are using query inside of a router.param in case someone comes looking for the answer.

    router.param('user_id', function(req, res, next, id){
      var query = User.findOne({_id:id});
    
      query.populate('pollsCreated').exec(function(err, user){
        if(err){return next(err)}
        if(!user){return next(new Error('can\'t find user'))}
    
        req.user = user;
        next();
      })
    })