2

我的任务是向站点添加 Angular Typeahead 搜索字段,并且数据需要来自多个表。它需要是一种“搜索所有事物”类型的查询,可以在一个位置查找人员、服务器和应用程序。

我在想最好的方法是在 Sails 中有一个 API 端点,它可以从同一个数据库上的 3 个表中提取并发送结果,但我不太确定如何去做。

4

1 回答 1

1

使用内置的bluebird 库,特别是Promise.all()。要处理结果,请使用.spread()。示例控制器代码(根据您的情况进行修改):

var Promise = require('bluebird');

module.exports = {

    searchForStuff: function(req, res) {
        var params = req.allParams();
        // Replace the 'find' criteria with whatever suitable for your case
        var requests = [
            Person.find({name: params.searchString}),
            Server.find({name: params.searchString}),
            Application.find({name: params.searchString})
        ];
        Promise.all(requests)
        .spread(function(people, servers, applications) {
            return res.json({
                people: people,
                servers: servers,
                applications: applications
            })
        })
    }

}
于 2016-01-30T11:00:01.920 回答