您可能在错误的地方寻找文档。它不在具有云功能的 Firestore/Extend 中。它在 Firestore 基本文档中,但您必须将代码类型切换为 node-js。 https://firebase.google.com/docs/firestore/query-data/order-limit-data
您必须通过两个查询来收集数据:在今天和未来的集合中。
通过这些查询,您可以获得文档及其数据。
比你只需要在过去制作一个文档,今天删除并制作一个新的文档(或重写现有的文档),并在将来删除。
我将如何在一个简单的可调用函数中做到这一点:
exports.scheduledFunction = functions.pubsub.schedule('0 0 * * *')
.onRun(async (context) => {
try {
let queryToday = admin.firestore().collection('today'); //you can add .limit(1)
const todaySnapshot = await queryToday.get();
const todayDoc = todaySnapshot.docs[0];
const todayData = todayDoc.data();
const todayToPastRef = admin.firestore().doc(`past/${todayData.documentUid}`);
/* or how the id is stored? you can just call
const todayToPastRef = admin.firestore().collection('past').doc()
and it will be generated automatically
*/
const promises = [];
promises.push(todayToPastRef.set(todayData));
let queryFuture = admin.firestore().collection('future').orderBy('date').limit(1);
/*
or how is the date stored? Idk if firebase allows to query by Timestamp
you just want to fetch the closest date after today so the order is ascending
*/
const futureSnapshot = await queryFuture.get();
const futureDoc = futureSnapshot.docs[0];
const futureData = futureDoc.data();
const futureToTodayRef = admin.firestore().doc(`today/${futureData.documentUid}`);
promises.push(futureToTodayRef.set(todayData));
promises.push(futureDoc.ref.delete());
promises.push(todayDoc.ref.delete());
/*
or you can try to change today's doc data, but the id will remain the same
promises.push(todayDoc.ref.update(futureData))
*/
return Promise.all(promises); // function will be executed after all the promises are fullfilled or rejected
} catch (err) {
return Promise.reject(err);
}
});
请注意,我使用 async/await 而不是 .then() 和 .catch()。
使用 console.log() 进行调试,并尝试使用 VSCode,这样您就可以检查对象的方法和属性,这很有帮助
更新:
是的,你可以用一批来做。还有一个例子:
exports.scheduledFunction = functions.pubsub.schedule('0 0 * * *').onRun((context) => {
const db = admin.firestore();
let queryToday = db.collection('today');
let queryFuture = db.collection('future').orderBy('date').limit(1);
const batch = db.batch();
return queryToday
.get()
.then(todaySnapshot => {
const todayDoc = todaySnapshot.docs[0];
const todayData = todayDoc.data();
const todayToPastRef = db.doc(`past/${todayData.docUid}`);
batch.set(todayToPastRef, todayData);
batch.delete(todayDoc.ref);
return queryFuture.get();
})
.then(futureSnapshot => {
const futureDoc = futureSnapshot.docs[0];
const futureData = futureDoc.data();
const futureToTodayRef = db.doc(`today/${futureData.docUid}`);
batch.set(futureToTodayRef, futureData);
batch.delete(futureDoc.ref);
// now two operations are completed, you just can commit the batch
return batch.commit();
})
.catch(err => {
// if todaySnapshot or futureSnapshot were not fetched, batch wont be commited
// or, for example, if snapshots were empty
return Promise.reject(err)
});
});
您还可以使用 .getAll() 或类似的方法并行获取文档。你应该测试和实验