在Node.js中,与谷歌云数据存储(Google Cloud Datastore)进行交互,通常使用@google-cloud/datastore
库。以下是一些基本的查询示例,涵盖了不同类型的查询。
首先,确保你已经安装了@google-cloud/datastore
库。如果没有,请运行以下命令进行安装:
npm install @google-cloud/datastore
在你的Node.js应用中,初始化一个Datastore客户端:
const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
async function getEntity(kind, id) {
const entityKey = datastore.key([kind, id]);
const [entity] = await datastore.get(entityKey);
return entity;
}
async function getEntities(kind, filters = []) {
const query = datastore.createQuery(kind).filter(...filters);
const [entities] = await datastore.runQuery(query);
return entities;
}
async function getUsersByEmail(email) {
const users = await getEntities('User', [
datastore.filter('email', '=', email)
]);
return users;
}
async function getUsersByAgeOrCountry(age, country) {
const users = await getEntities('User', [
datastore.or(
datastore.filter('age', '=', age),
datastore.filter('country', '=', country)
)
]);
return users;
}
async function getTopUsers(limit = 10) {
const users = await getEntities('User', [], [
datastore.order('score', { descending: true }),
datastore.limit(limit)
]);
return users;
}
领取专属 10元无门槛券
手把手带您无忧上云