按子值查找文档?
Find documents by child value?
我需要找到带有 name: "Nick"
的所有文档 ID,以便我可以更新 score
。
我有以下 Firestore Database
结构:
{
"c4ca4238a0b923820dcc509a6f75849b": {
title: "Tiger",
user: {
name: "Chris",
score: 1
}
},
"c81e728d9d4c2f636f067f89cc14862c": {
title: "Lion",
user: {
name: "Nick",
score: 2
}
}
}
从 documentation 我看到我可以像这样使用 where
找到文档:
const dbQuery = query(collection(dbFirestore, "posts"), where("title", "==", "Tiger"));
const dbSnapshot = await getDocs(dbQuery);
dbSnapshot.forEach((result) => {
console.log(result.id, " => ", result.data());
});
但是我没有看到任何有关如何按子元素搜索的内容 (user.name
)?
Firestore 是一个 NoSQL 数据库,它继承了您在任何其他 NoSQL 数据库上的查询方式。要在 embedded/nested 文档中的字段上指定查询条件,请使用圆点表示法 "field.nestedField"
。使用点号查询时,字段和嵌套字段必须在引号内。
您可以使用此示例查询从嵌套对象中获取所有文档:
const dbQuery = query(collection(db, "posts"), where("user.name", "==", "Nick"));
const dbSnapshot = await getDocs(dbQuery);
dbSnapshot.forEach((result) => {
console.log(result.id, " => ", result.data());
});
我需要找到带有 name: "Nick"
的所有文档 ID,以便我可以更新 score
。
我有以下 Firestore Database
结构:
{
"c4ca4238a0b923820dcc509a6f75849b": {
title: "Tiger",
user: {
name: "Chris",
score: 1
}
},
"c81e728d9d4c2f636f067f89cc14862c": {
title: "Lion",
user: {
name: "Nick",
score: 2
}
}
}
从 documentation 我看到我可以像这样使用 where
找到文档:
const dbQuery = query(collection(dbFirestore, "posts"), where("title", "==", "Tiger"));
const dbSnapshot = await getDocs(dbQuery);
dbSnapshot.forEach((result) => {
console.log(result.id, " => ", result.data());
});
但是我没有看到任何有关如何按子元素搜索的内容 (user.name
)?
Firestore 是一个 NoSQL 数据库,它继承了您在任何其他 NoSQL 数据库上的查询方式。要在 embedded/nested 文档中的字段上指定查询条件,请使用圆点表示法 "field.nestedField"
。使用点号查询时,字段和嵌套字段必须在引号内。
您可以使用此示例查询从嵌套对象中获取所有文档:
const dbQuery = query(collection(db, "posts"), where("user.name", "==", "Nick"));
const dbSnapshot = await getDocs(dbQuery);
dbSnapshot.forEach((result) => {
console.log(result.id, " => ", result.data());
});