【发布时间】:2021-09-11 11:22:26
【问题描述】:
我正在使用 Node.js(我很新)和 Google Cloud Firestore 数据库来保存文档,根据:
- 用户
- 推文
一个用户文档,即一个用户,在子集合“推文”中有许多推文。我有兴趣将用户连同子集合中的最后一条推文一起检索,所以我得到了一个这样的 JSON 文件。换句话说,这就是我想要得到的:
users: {
{
name:'john',
twitter_username:'johnny',
tweets: {
text: "I am called johnny, this is my tweet",
created_at: "2021-06-29 12:00:00"
},
},
{
name:'anne',
twitter_username:'anne',
tweets: {
text: "I am called anne, this is another tweet",
created_at: "2019-06-28 12:00:00"
},
}
}
我有这个功能:
function getUserData() {
return db.collection('users').get()
.then((querySnapshot) => {
var docs = querySnapshot.docs.map(doc => [doc.data(), doc.id]);
//console.log(docs);
return docs
如果我可以用最后一条推文获取并替换 doc.id(即用户文档 ID),我想会解决它。但是我该怎么做呢?
任何其他解决方案(可能带有 for 循环)也可以。我在这个看似简单的问题上花了几个小时,但无法让它同时返回用户数据和推文数据。
编辑 2:
我意识到我可以做到这一点:
function getUserData() {
return db.collection('users').get()
.then((querySnapshot) => {
var docs = querySnapshot.docs.map(doc => [doc.data(), doc.id, getStuff(doc.id)])
console.log(docs)
return docs
});
}
function getStuff(doc_id) {
return db.collection('users').doc(doc_id).collection('tweets').limit(1).get()
.then((querySnapshot) => {
var docs = querySnapshot.docs.map(doc => doc.data());
console.log("TWEETS", doc_id, docs[0]['text']);
return docs[0]['text']
});
}
产生的日志结果为:
TWEETS DAU86mxIhmD6qQQpH4F God’s country!
TWEETS JQHTO0jUjAodMQMR6wI I’m almost there Danny!
来自 getStuff 函数。
现在唯一的问题是我无法让 map 函数等待 getStuff,所以 return docs 为 getStuff(doc.id) 返回一个 Promise { <pending> }。
我不熟悉 Promises 和 await/async,我无法让它工作。解决这个 Promise pending -> twitter text 将解决我的问题。我该怎么做?
【问题讨论】:
标签: node.js google-cloud-firestore