NodeJS 如何在创建口袋妖怪时从另一个模型添加属性?

dw1jzc5e  于 2023-05-28  发布在  Node.js
关注(0)|答案(1)|浏览(182)

你好,我正在使用口袋妖怪API来制作一个reactjs应用程序。在我的控制器中,我有以下方法来创建一个口袋妖怪:

const createPokemon = async (name, hp, attack, defense, speed, height, weight, types, image) => {

  console.log(types)

  const newPokemon = await Pokemon.create({
    name,
    hp,
    attack,
    defense,
    speed,
    height,
    weight,
    image
  })

types.forEach(async (t) => {
  console.log(t)
  const type = await Type.findOne({
    where: {
      name: t,
    }
  })
  console.log(type)
  await newPokemon.addType(type)
})


return newPokemon;

}

这是我的类型列表:

[
  {
    "name": "normal"
  },
  {
    "name": "fighting"
  },
  {
    "name": "flying"
  },
  {
    "name": "poison"
  },
  {
    "name": "ground"
  },
  {
    "name": "rock"
  },
  {
    "name": "bug"
  },
  {
    "name": "ghost"
  },
  {
    "name": "steel"
  },
  {
    "name": "fire"
  },
  {
    "name": "water"
  },
  {
    "name": "grass"
  },
  {
    "name": "electric"
  },
  {
    "name": "psychic"
  },
  {
    "name": "ice"
  },
  {
    "name": "dragon"
  },
  {
    "name": "dark"
  },
  {
    "name": "fairy"
  },
  {
    "name": "unknown"
  },
  {
    "name": "shadow"
  }
]

当我创建一个口袋妖怪时,我传递了口袋妖怪的所有属性,包括来自Type模型的type属性。
我在创建t时传递它。所以我想在我的类型列表中找到t并将其添加到我的口袋妖怪中。
这是我的请求:

{
    "name": "juann",
    "hp": 61,
    "attack": 64,
    "defense":43,
    "speed": 68,
    "height": 10,
    "types": ["poison", "normal"]

}

console.log(types)
显示["poison", "normal"]
console.log(t)打印poisonnormal
但是当console.log(type)的时候我在控制台中得到null和null

odopli94

odopli941#

您不应该将forEachawait一起使用:

const createPokemon = async (
  name,
  hp,
  attack,
  defense,
  speed,
  height,
  weight,
  types,
  image
) => {
  console.log(types);

  const newPokemon = await Pokemon.create({
    name,
    hp,
    attack,
    defense,
    speed,
    height,
    weight,
    image,
  });

  for (const t of types) {
    const type = await Type.findOne({
        where: {
          name: t,
        },
    });
    console.log(type);
    await newPokemon.addType(type);
  }

  return newPokemon;
};

相关问题