情况是这样的:
我有3个模型的数据库:
宠物小精灵/宠物小精灵类型/类型
宠物小精灵通过PokemonType链接到一个或多个Type。
所以现在我想要一个函数来获取链接到给定Pokemon的Types:
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行,我希望Type表中属于该PokemonType行的类型。
但是,当尝试使用模型执行此操作时,我一直保持未定义状态和[object Object]。
我知道如果我使用Pokemon.find,它会使用表来搜索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中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句