首页 > 解决方案 > Google Cloud Datastore 从数组中获取对象

问题描述

如何使用 NodeJs Datastore SDK 通过 id 从数组属性中检索对象?

我有一个名为 Team 的 Kind,其属性为 Players。我需要通过 id 获得一个玩家。

这是团队实体的示例:

{
    "id" : "T01",
    "name" : "My Team",
    "city" : "London",
    "players" : [
        {
            "id" : "P01",
            "name" : "John",
            "lastName" : "Doo",
            "height" : "181"
        },
        {
            "id" : "P02",
            "name" : "Mario",
            "lastName" : "Rossi",
            "height" : "185"
        }
    ]
}

标签: node.jsgoogle-cloud-datastore

解决方案


一种可能的解决方案是查询所有 Teams,然后使用for 循环搜索每个 Team 的player属性。下面的示例将其值声明并设置为与所需 ID 匹配的 Player 对象数组:queryResult

  const query = datastore.createQuery('Team');
  const desiredId = "P01";

  const queryResult = await datastore.runQuery(query).then(results => {
     const teams = results[0];
     let players = [];
     teams.forEach(team => {
         // Below we search for a valid player with the desired ID
         const matchedPlayer = team.players.find(player => player.id == desiredId);
         // If we find a valid player we "push it" to the players array.
         if(matchedPlayer) {
             players.push(matchedPlayer);
         }
     });
     return players;
  });

推荐阅读