LoopBack 访问另一个模型

LoopBack access another model

情况是这样的:

我的数据库有 3 个模型:

精灵宝可梦 / PokemonType / 类型

Pokemon 通过 PokemonType 链接到一种或多种类型。

所以现在我想要一个函数来获取链接到给定口袋妖怪的类型:

module.exports = function(Pokemon) {


    Pokemon.types = function(id, cb){
        var PokemonType = Pokemon.app.models.pokemonType.find();
        var Type = Pokemon.app.models.type.find();
        var arrayTypes = [];

        // var result = app.models.pokemonType.find({where : {"pokemon_id": id}});
//      for(var x in result){
//          var typeId = x.pokemonType_id;
//          var results = Type.find({where: {"id": typeId}});
//          arrayTypes.push(results);
//      }
        cb(null, PokemonType[0] + " AND " + Type);
    }

    Pokemon.remoteMethod(
        'types', {
            accepts: {arg: 'id', type:'number', required:true, http: { source: 'header' }},
            returns: {arg: 'types', type:'object' },
            http: {path: '/types', verb: 'get', status: 200, errorStatus: 400}
        }   
    );
};

我正在尝试从 PokemonType table 的结果中查找类型。因此,如果当前 PokemonID​​ 有 1 行,我希望类型 table.

中属于此 PokemonType 行的类型

然而,当我尝试对模型执行此操作时,我一直得到未定义和 [o​​bject Object]。

我知道如果我使用 Pokemon.find 它会使用 table 来搜索 Pokemon,但是如果我使用给定的 PokemonID​​ 搜索 PokemonType,它是否具有相同的实例?还是我的想法完全错了?

我是什么意思?我希望这样:

PokemonType.find({where :{ "pokemon_id": id}}); 

与以下行为相同:

Pokemon.find({where: { "id": id}});

但答案正确。

如何解决未定义的问题?然后我如何获得与口袋妖怪相关联的正确类型?

找到的解决方案:

Pokemon.types = function(id, cb){
        var PokemonType;
        var curPokemon = {"pokemon":null, "type": null};
        var Type;
        var arrayTypes = new Array();
        var count;

        Pokemon.find({where: {"id": id}})
        .then(result => {
            if(result.length > 0){
                curPokemon.pokemon = result[0];
                Pokemon.app.models.pokemonType
                .find({where:{"pokemon_id": id}})
                .then(result => {
                    count = result.length
                    result.forEach(function(item, index){
                        Pokemon.app.models.type
                        .find({where:{"id": item.type_id}})
                        .then(result => {
                            if(result.length > 0){
                                arrayTypes.push(result[0]);
                                if(arrayTypes.length == count){
                                    curPokemon.type = arrayTypes;
                                    cb(null, curPokemon);
                                }
                            }
                        });
                    });
                });
            }
        });
    }

通过使用 MainModel.app.models.ModelIWant 我可以获得正确的模型实例。然后使用 .find 并在 promise (.then) 中使用我的逻辑。

这让我得到了正确的结果,然后使用这些结果得到了正确的数据。然后通过使用 curPokemon 制作自己的模型(对象),我可以修改结果,以便将所需数据添加到 MainModel。