javascript - Firebase 查询示例返回无用的对象
问题描述
我正在尝试使用查询从 firebase 文档中获取示例,但它似乎不起作用。我正在使用云火库。
这是我得到的结果:
var citiesRef = db.collection("cities");
citiesRef.doc("SF").set({
name: "San Francisco", state: "CA", country: "USA",
capital: false, population: 860000,
regions: ["west_coast", "norcal"] });
citiesRef.doc("LA").set({
name: "Los Angeles", state: "CA", country: "USA",
capital: false, population: 3900000,
regions: ["west_coast", "socal"] });
citiesRef.doc("DC").set({
name: "Washington, D.C.", state: null, country: "USA",
capital: true, population: 680000,
regions: ["east_coast"] });
citiesRef.doc("TOK").set({
name: "Tokyo", state: null, country: "Japan",
capital: true, population: 9000000,
regions: ["kanto", "honshu"] });
citiesRef.doc("BJ").set({
name: "Beijing", state: null, country: "China",
capital: true, population: 21500000,
regions: ["jingjinji", "hebei"] });
// Create a reference to the cities collection
var citiesRef = db.collection("cities");
// Create a query against the collection.
var query = citiesRef.where("state", "==", "CA");
console.log(query);
我期望记录一个代表包含指定值的文档的对象。但结果总是相同的(见附件),即使我搜索一个不存在的值。这是为什么?我希望有人可以解释这里发生了什么以及为什么文档中提供的示例不起作用...
解决方案
这是因为,使用问题中的代码,您定义(和console.log()
)一个Query对象。
您实际上不应该直接使用此对象,而是:
- 调用
get()
方法执行查询并获取结果文档(通过 aQuerySnapshot
); 使用方法为
QuerySnapshot
事件附加监听器onSnapshot()
或者,使用 , 等其他方法优化此
where()
查询orderBy()
...
您可以在此处找到完整的文档:https ://firebase.google.com/docs/reference/js/firebase.firestore.Query
因此,更具体地说,使用您当前的代码,您应该执行以下操作:
var query = citiesRef.where("state", "==", "CA");
query.get()
.then(snapshot => {
if (!snapshot.empty) {
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
} else {
console.log('No document corresponding to the query');
}
})
.catch(err => {
console.log('Error getting documents', err);
});
推荐阅读
- laravel - Laravel:Vue组件无法识别
- php - 如何为有回复的评论显示显示回复按钮?
- laravel - Laravel Vue - 存储数组
- java - 延迟来自队列rabbitmq spring的消息
- reactjs - 如何更快地更新 React Native 应用程序中的 ERC20 代币数量?
- python - 点云缩小
- c# - 如何从表示为字符串的访问控制列表中制作 SystemAcl 对象?
- python-3.x - 通过网络将数据并行发送到多个接收者
- ios - 使用令牌的 WKWebview 身份验证不起作用 - Swift
- html - SVG 文本标签未在组上方呈现