2016-04-07 7 views
2

をアクセスもこれは状況です:ループバックが別のモデル

私は3つのモデルで、私のデータベースを得た:

ポケモン/ PokemonType /タイプ

はAポケモンは、一つ以上のタイプにPokemonTypeを介して連結されています。

は、だから今は、関数が与えられたポケモンにリンクされているタイプを取得したい:私は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} 
     } 
    ); 
}; 

。したがって、現在のPokemonID​​に1行がある場合は、このPokemonType行に属するタイプをTypeテーブルから削除します。

しかし、モデルでこれをしようとすると、私は未定義と[オブジェクトオブジェクト]を取得し続けます。

私はPokemon.findを使用するとテーブルを使用してポケモンを検索しますが、指定したPokemonID​​でPokemonTypeを検索すると同じインスタンスがあることは知っていますか?それとも、私は完全に間違っていると思いますか

どういう意味ですか?

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

が、正しい答えを:

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

と同じように行動する:私はこれを期待しています。

未定義の問題を解決するにはどうすればよいですか?そして、私はどのように正しいタイプをポケモンにリンクさせるのですか?見つかっ

答えて

0

解決策:

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を使って約束の中で自分の論理を使う(.then)。

これにより、正しい結果が得られ、これらの結果を使用して正しいデータを取得することができました。 curPokemonで独自のモデル(オブジェクト)を作成することで、結果を変更して希望のデータをMainModelに追加することができました。

関連する問題