在我的Cloud Firestore数据库中,始终注册一个用户,该数据库存储事件发生的时间:
const p = usersReference.add({
...,
registerTime: admin.firestore.FieldValue.serverTimestamp(),
...
});
我的目标是创建另一个云功能,该功能将用户作为输入并在用户注册至少有5天后返回:
export const get_user_timeleft = functions.https.onRequest((request, response) => {
//useless part of the function...
querySnapshot.forEach(function (documentSnapshot) {
//Here I know that documentSnapshot.data().registerTime
//returns whatever is saved in the database.
//How can I return true or false if there's been 5
//or more days since the user registered?
response.json(TRUE of FALSE);
})
}
})
.catch(function(error) {
response.json(error);
});
});
很明显,我可以再次调用admin.firestore.FieldValue.serverTimestamp()
并尝试将它们相减,但是我什至不知道它的类型。过去,我曾经设法将Date
用作Date
,但由于Firebase认为distance
将被弃用,因此我不知道如何处理它。
答案 0 :(得分:1)
如果您想在Cloud Function中检查querySnapshot.forEach()
循环返回的每个文档,如果距用户注册(即today - registerTime > 5
)至少有5天,则可以执行如下:
export const get_user_timeleft = functions.https.onRequest((request, response) => {
//useless part of the function...
const nowDate = new Date();
querySnapshot.forEach(function (documentSnapshot) {
//Here I know that documentSnapshot.data().registerTime
//returns whatever is saved in the database.
//How can I return true or false if there's been 5
//or more days since the user registered?
const elapsedTime = (nowDate.getTime() - documentSnapshot.data().registerTime.getTime());
const daysDifference = Math.floor(elapsedTime/1000/60/60/24);
//Check that the difference is more than 5 and then act accordingly
//It is not crystal clear from your question if there is only one document in the querySnapshot
})
})
.catch(function(error) {
response.json(error);
});
});
如果您确定知道查询仅返回一个文档(根据您所提问题的注释,情况似乎确实如此),您可以执行以下操作:< / p>
export const get_user_timeleft = functions.https.onRequest((request, response) => {
//useless part of the function...
const nowDate = new Date();
let daysDifference;
querySnapshot.forEach(function (documentSnapshot) {
//Here I know that documentSnapshot.data().registerTime
//returns whatever is saved in the database.
//How can I return true or false if there's been 5
//or more days since the user registered?
const elapsedTime = (nowDate.getTime() - documentSnapshot.data().registerTime.getTime());
daysDifference = Math.floor(elapsedTime/1000/60/60/24);
});
if (daysDifference > 5) {
response.send({ result: true });
} else {
response.send({ result: false });
}
})
.catch(function(error) {
response.json(error);
});
});