我有游戏收藏:
{
"name": "Play RoadRash",
"version": "1.0.0",
"icon": "image-md-two-thirds.png",
"id": "6dc41c3fa0e7"
}
和平台集合:
{
"name": "PlayStation",
"version": "7",
"icon": "playstation.jpg",
"id": "55eaf322f1a16"
}
我正在尝试创建一个搜索查询,根据名称参数在两个集合中进行搜索。有没有人知道如何在帆水线中搜索多个集合?
答案 0 :(得分:2)
我们在所有模型中编写了一个带全文搜索的控制器。它所做的就是通过请求中的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
及其中。它仍然需要重构此代码,但它可以工作。