猫鼬:填充所有子对象

Mongoose: populate all sub objects

我使用的是通用 rest api,它允许在请求中传递 mongo 集合名称并提供其内容。

我的 LIST 命令如下所示:

router.get('/:collectionName', function(req, res, next) {
    req.collection.find().sort('-created_on').exec(function(e, results){
        if (e) return next(e);
        res.send(results)
    });
});

效果很好。

我的问题是我希望每个列表查询都填充子对象(如果存在)。

我试过了:

req.collection.find().populate().sort..

但显然我得到一个错误:

TypeError: utils.populate: invalid path. Expected string. Got typeof undefined

帮忙?

最后我不得不修补它:

router.get('/:collectionName', function(req, res, next) {
    var populationQuery = [];
    var paths = req.collection.schema.paths;
    for (var path in paths) {
        if (paths[path].caster) {
            populationQuery.push({path: path});
        }
    }
    req.collection.find().populate(populationQuery).sort('-created_on').exec(function (e, results) {
        if (e) return next(e);
        console.log(results);
        res.send(results)
    });
});

这可行,但我想应该有更好的解决方案