简体   繁体   中英

How to query through nested keys in Google datastore?

I have users, stored under specific unique IDs. I need to query them by a certain property, but I cannot figure out how to do that when my unique ID is part of the key.

const user1 = {
    id: 1,
    name: 'John Smith',
    cityId: 102,
};

const user1 = {
    id: 2,
    name: 'Rudy Black',
    cityId: 102,
};

const upsertUser = user => {
    const key = datastore.key([ 'users', user.id ]);

    return datastore.upsert({ key, data: user });
});

const getUsersInCity = async cityId => {
    const query = datastore.createQuery('users').filter('cityId', '=', cityId);

    const [ users ] = await datastore.runQuery(query);

    return users;
};

upsertUser(user1);
upsertUser(user2);

console.log(await getUsersInCity(102)); // Expected: John Smith, Rudy Black

An example of code that you can give it a try using to query values via ID, it's using the below code:

const key = this.datastore.key(['Customer', id:number]);
await this.datastore
  .get(key)
  .then(results => {
    console.log(results);
  })
  .catch(err => { console.error('ERROR:', err); });

This code was get from the article Google DataStore Query By Nodejs . This article provides some good examples of queries that you can give a look.

I would recommend you to take a look at it and use the above code as a start point.

Let me know if the information helped you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM