我有游戏收藏:
{
"name": "Play RoadRash",
"version": "1.0.0",
"icon": "image-md-two-thirds.png",
"id": "6dc41c3fa0e7"
}
和平台集合:
{
"name": "PlayStation",
"version": "7",
"icon": "playstation.jpg",
"id": "55eaf322f1a16"
}
我试图创建一个搜索查询谁搜索在两个集合基于名称参数。有人知道如何在帆水线上搜索多重收集吗?
我们已经在所有模型中编写了一个具有全文搜索功能的控制器。它所做的就是根据请求中的q
参数在所有模型及其属性中搜索。以下是该控制器的完整代码:
var _ = require('lodash');
var Promise = require('bluebird');
module.exports = {
index: function (req, res) {
var models = [];
if (!req.param('q')) {
return res.badRequest(null, null, 'You should specify a "q" parameter!');
}
var q = req.param('q');
if (req.param('model')) {
var modelStr = req.param('model').toString().toLowerCase();
if (!(modelStr in sails.models)) {
return res.badRequest(null, null, 'Cannot find model: ' + modelStr);
}
models.push({name: modelStr, model: sails.models[modelStr]});
} else {
_.forEach(sails.models, function (model, modelStr) {
models.push({name: modelStr, model: model});
});
}
Promise.map(models, function (modelObj) {
var model = modelObj.model;
var modelStr = modelObj.name;
var where = _.transform(model.definition, function (result, val, key) {
result.or.push(_.set({}, key, {contains: q}));
}, {or: []});
return model
.find(where)
.then(function (queryRes) {
var resObj = {};
resObj[modelStr] = queryRes;
return Promise.resolve(resObj)
});
})
.then(function (searchRes) {
return _.transform(searchRes, function (result, val) {
result = _.merge(result, val);
}, {});
})
.then(res.ok)
.catch(res.serverError)
}
};
你可以把它复制粘贴到你的api/controllers/SearchController.js
中,就是这样。它仍然需要重构这段代码,但它可以工作。