簡體   English   中英

Google Cloud Datastore從數組獲取對象

[英]Google Cloud Datastore get an object from array

如何使用NodeJs Datastore SDK通過數組屬性按ID檢索對象?

我有一個名為Team的屬性玩家。 我需要按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"
        }
    ]
}

像這樣的示例使用SDK可能會有所幫助。

https://github.com/googleapis/nodejs-datastore/blob/master/samples/tasks.list.js

它使用查詢:

  const query = datastore.createQuery('Task').order('created');

因此,從理論上講,您可以這樣做:

  const query = datastore.createQuery('Team').filter('player.id', '=', playerId);

一種可能的解決方案是查詢所有Team,然后使用for循環搜索每個Team的玩家屬性。 下面的示例聲明queryResult並將其值設置為與所需ID匹配的Player對象數組:

  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;
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM