Jade renders unexpected values in templates for "populated" mongoose properties

I have a jade template where I'm printing out properties from a mongoose object. The object has properties that were populated via mongoose's dbref-like populate feature. When The template renders I get nonsense.

simplified example:

in the route

User.findById(req.params.user, function(err, user){
  res.render('training', {training:user.training});
}).populate('training.details');

in the template:

a.training-link(href='/training/#{training.details.id}') ...

in the browser:

<a href="/training/O &gt;°Cm5�" class="training-link">...</a>

The first time the page is loaded, where I would expect a regular mongo hexadecimal string (4fac4e5f379cb0a68100015d) I get something like "O >°Cm5�". This only happens on the first page load after a server restart. All subsequent page loads render as expected.

What's happening here and how can I fix it?

Thanks.

This is a bit embarrassing but I figured it out.

There is a logical branch in our app that, for various reasons, causes the code in my question above to run on the second and subsequent loads but not on the first. The other branch, which only runs on the first load, makes a similar query but I hadn't added populate('training.details') to it. I believe the nonsense string O¬N_7°¦� is the result of calling .id on an ObjectId object rather than the populated training.details.

Looks like we need to refactor some code.