我无法在Firestore中的查询中获取应用程序的值。我想用EJS渲染组和apps集合的值,但是从firestore那里的THEN之后,app的值被删除了,之后我就不能使用它们了。
我尝试使用lodash const appsClone = _.cloneDeep(apps);
,但没有成功。
apps集合在groups集合内。
以下是我要执行的操作的示例:
let groups = [];
let apps = [];
const db = admin.firestore();
const group = db.collection('groups').where('roleId', '==', req.session.idRol);
group.get() // Trying to get all the groups
.then(snapshot => {
snapshot.docs.forEach(grp => {
groups.push(grp.data()); // I can get all the groups without any problem
grp.ref.collection('apps').get() // once I get the groups I try to get the APPS collection inside every group
.then(snapshot2 => {
snapshot2.docs.forEach(app => {
apps.push(app.data()); // I can get the values of app and apps without any problem
console.log(apps); // I can get the value here of apps still
})
// Now I cant get the value
// And I cant render here because I need the missing groups in the last forEach
})
});
console.log("APPS: " + apps); // Here apps is empty
res.render("pages/launchpad", { groups, apps }); // Get to render groups but varible apps is empty.
})
.catch(err => {
console.log(err);
})
});
})
.catch(err => {
console.log(err);
})
非常感谢您的帮助,祝您生活愉快。
答案 0 :(得分:1)
console.log("APPS: " + apps);
在您的诺言兑现之前就已执行。
在致电res.render
之前,您应该等待所有诺言都得到解决。这可以通过使用Promise.all
let groups = [];
let apps = [];
const db = admin.firestore();
const group = db.collection('groups').where('roleId', '==', req.session.idRol);
group.get() // Trying to get all the groups
.then(snapshot => {
return Promise.all(snapshot.docs.map(grp => {
groups.push(grp.data()); // I can get all the groups without any proble
return grp.ref.collection('apps').get() // once I get the groups I try to get the APPS collection inside every group
.then(snapshot2 => {
snapshot2.docs.forEach(app => {
apps.push(app.data()); // I can get the values of app and apps without any problem
console.log(apps); // I can get the value here of apps still
})
})
}))
.then(() => {
console.log("APPS: " + apps);
res.render("pages/launchpad", {
groups,
apps
});
})
})
.catch(err => {
console.log(err);
})
});
})
.catch(err => {
console.log(err);
})