在 sails js 中组合搜索

Combined search in sails js

我有游戏collection:

{
  "name": "Play RoadRash",
  "version": "1.0.0",
  "icon": "image-md-two-thirds.png",
  "id": "6dc41c3fa0e7"
}

和平台collection:

{
  "name": "PlayStation",
  "version": "7",
  "icon": "playstation.jpg",
  "id": "55eaf322f1a16"
}

我正在尝试创建一个搜索查询,它根据名称参数在 collection 中进行搜索。有谁知道如何在风帆吃水线上搜索多个 collection 吗?

我们已经编写了一个控制器,可以在所有模型中进行全文搜索。它所做的就是通过请求中的 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 即可。它仍然需要重构此代码,但它有效。