Firestore 查询仅返回 1 个文档
Firestore query is only returning 1 doc
我编写了一个简单的 Firebase 函数来获取名为 'events' 的集合中的所有文档。
我的代码:
export const requestuserroute2 = functions
.region("europe-west6")
.https.onRequest(async (request, response) =>{
const uid = String(request.query.uid);
const db = admin.firestore();
db.collection("position_data")
.doc(uid).collection("events")
.get()
.then((snapshot) => {
snapshot.forEach((doc) => {
const data = JSON.stringify(doc.data(), replaceg);
response.send(data);
});
});
});
replaceg是删除key为'g'的数据的函数。 (请无视)
只有returns第一个文档的内容(以*Mnija结尾):
{"timeStamp":1644760476557,"coordinates":{"_latitude":13.1,"_longitude":31.562},"sid":"b72b98b0-7130-41bd-9c67-ed79128c070a","type":"pause_off"}
我期望的是多行数据,每个文档 1 行。代码似乎没有遍历文档。那我哪里错了?
这是因为您在循环内向客户端发送响应:
snapshot.forEach((doc) => {
const data = JSON.stringify(doc.data(), replaceg);
response.send(data);
});
第一次通过循环将数据发送到客户端,所有其他时间调用都被忽略(它实际上应该引发错误,但是¯\_(ツ)_/¯)。
要将所有文档发送给调用者,请在循环中构建一个响应,然后然后发送:
db.collection("position_data")
.doc(uid).collection("events")
.get()
.then((snapshot) => {
const result = snapshot.docs.map((doc) => {
return JSON.stringify(doc.data(), replaceg);
});
response.send(result);
});
我编写了一个简单的 Firebase 函数来获取名为 'events' 的集合中的所有文档。 我的代码:
export const requestuserroute2 = functions
.region("europe-west6")
.https.onRequest(async (request, response) =>{
const uid = String(request.query.uid);
const db = admin.firestore();
db.collection("position_data")
.doc(uid).collection("events")
.get()
.then((snapshot) => {
snapshot.forEach((doc) => {
const data = JSON.stringify(doc.data(), replaceg);
response.send(data);
});
});
});
replaceg是删除key为'g'的数据的函数。 (请无视)
只有returns第一个文档的内容(以*Mnija结尾):
{"timeStamp":1644760476557,"coordinates":{"_latitude":13.1,"_longitude":31.562},"sid":"b72b98b0-7130-41bd-9c67-ed79128c070a","type":"pause_off"}
我期望的是多行数据,每个文档 1 行。代码似乎没有遍历文档。那我哪里错了?
这是因为您在循环内向客户端发送响应:
snapshot.forEach((doc) => {
const data = JSON.stringify(doc.data(), replaceg);
response.send(data);
});
第一次通过循环将数据发送到客户端,所有其他时间调用都被忽略(它实际上应该引发错误,但是¯\_(ツ)_/¯)。
要将所有文档发送给调用者,请在循环中构建一个响应,然后然后发送:
db.collection("position_data")
.doc(uid).collection("events")
.get()
.then((snapshot) => {
const result = snapshot.docs.map((doc) => {
return JSON.stringify(doc.data(), replaceg);
});
response.send(result);
});