问题
I have a find query that returns multiple results of an object, this object contains a model that contains another model, the thing is that waterline doesn't support nested populates, so it populates the first model but not it's inner model.
all the examples I've seen for that are for a findOne query, i am looking for a way to resolve that for a find query that returns multiple results.
This is my models structure:
// Container.js
widgets: {
model: 'websitewidget'
}
// WebsiteWidget.js
html: {
model: 'widgethtml'
}
// WidgetHtml.js
source: {
type: 'String'
}
my query returns all the containers, and it populates the WebsiteWidget inside it, but won't populate the WidgetHtml model inside WebsiteWidget.
This is my code so far, I would appreciate if someone will tell me what I'm doing wrong:
async.auto({
//First get the containers
container: function(cb) {
Container.find()
.where({
website: options.websiteId,
or: [
{ 'layout': '' },
{ 'layout': options.page.layout, page: (options.page.layout == 'default' ? 0 : options.page.id) } // TODO: perhaps there's a better way of doing it? instead of limiting page to default name.
]
})
.populate('widgets')
.exec(cb);
},
// Then all of the widget's widgetHtmls, using an "in" query by
// setting "id" criteria to an array of user IDs
widgetsHtml: ['container', function(cb, results) {
WidgetHtml.find({id: _.pluck(results.container.widgets, 'widgets')}).exec(cb);
}],
// Map the comment users to their comments
map: ['widgetsHtml', function(cb, results) {
// Index widget's widgetHtml by ID
var widgetsHtml = _.indexBy(results.widgetsHtml, 'id');
// Get a plain object version of container & widgets
var container = results.container[0];
// Map users onto comments
container.widgets = container.widgets.map(function(widget) {
widget.widgetHtml = widgetsHtml[widget.widgetHtml];
return widget;
});
return cb(null, container);
}]
},
// After all the async magic is finished, return the mapped result
// (or an error if any occurred during the async block)
function finish(err, results) {
if (err) {return res.serverError(err);}
return res.json(results.map);
}
);
来源:https://stackoverflow.com/questions/29588582/sails-js-waterline-nested-populate-query