Danpe
Danpe

Reputation: 19047

Mongoose Populate with express res.json() breaks

So I'm selecting Activities from the mongodb and populating User for each.

var query = Activity.find(query).populate("user");
return query.sort({created:"desc"}).exec(function(err, activities) {
    debugger;
    if (!err) {
        return res.json(activities);
    } else {
        res.status(400).json(err);
    }
});

As you can see I have a debugger; breakpoint is there, When I'm pring activities it prints an array of activities with the user object populated. Also when I'm calling something like activities[0].toJSON() I get everything good!

But the response comes back with the user property empty !

I looked into the source of express.response.json(OBJ) and saw this line:

var body = JSON.stringify(val, replacer, spaces); val is my activities

When calling JSON.stringify(activities) it will create a json with an empty user field.. any suggestions ?

Upvotes: 0

Views: 2105

Answers (1)

Gabriel L.
Gabriel L.

Reputation: 1699

Try the lean option. That gives back plain JS objects with no mongoose weirdness. Also, your error handling seems a little awkward, can be simplified.

var query = Activity.find(query).populate("user");
query.sort({created:"desc"}).lean().exec(function(err, activities) {
    if (err) return res.status(400).json(err);
    res.json(activities);
});

I would go even further, not hard-coding error sending in routes but simply passing along via if (err) return next(err) to error-handling middleware defined elsewhere in your app. You can still set the status, then use detection in your middleware, something like this:

app.use(function(err, req, res, next){
    err.status = err.status || 500;
    res.status(err.status).json(err);
});

Upvotes: 3

Related Questions