2016-04-07 15 views
2

情況是這樣的:環回存取權限另一種模式

我得到了我的數據庫有3種型號:

口袋妖怪/ 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} 
     } 
    ); 
}; 

我試圖從PokemonType表的結果找到的類型。所以如果當前PokemonID​​有1行,我想要屬於這個PokemonType行的類型超出Type表。

但是,當試圖與模型做到這一點,我不斷收到未定義和[對象對象]。

我知道如果我使用Pokemon.find,它使用表來搜索寵物小精靈,但是它是否有相同的實例,如果我用給定的PokemonID​​搜索PokemonType?或者我認爲完全錯誤?

我的意思是?我希望這樣的:

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

行動一樣:

Pokemon.find({where: { "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並在promise(.then)中使用我的邏輯。

這使我得到正確的結果,然後使用這些結果來獲取正確的數據。然後通過使用curPokemon創建自己的模型(對象),我可以修改結果,以便將所需數據添加到MainModel。