((已解决))
希望获得一些帮助来解决这个问题,首先我是 JS 和 Firebase 的新手,所以我可能会错过这里的明显内容。在任何情况下,我都试图将时间戳变成负数,以订购文档,如果我在查询调用中限制它们,则始终获得最新的 10 个。
但是,当尝试在 Cloud Functions 中运行下面的代码时会抛出错误。
但是,如果我在 (-Math.abs(timestamp)) 客户端进行 console.log,我得到一个负数就好了。这里有人可以帮助解决这个问题和/或提供解决方法吗?
// create welcome post on new user signup
exports.createWelcomePost = functions.auth.user().onCreate((user) => {
const uid = user.uid;
const userName = user.displayName;
const photoURL = user.photoURL;
const timestamp = admin.firestore.FieldValue.serverTimestamp();
const order = -Math.abs(timestamp);
const db = admin.firestore();
const docRef = db.collection('posts');
docRef.add({
order: order,
created: timestamp,
createdBy: uid,
userName: displayName,
userImage: photoURL,
content: "...just joined the Startly Community, let's give him a warm welcome!",
featuredImage: "assets/img/welcome_post.jpg"
})
.then((docRef) => {
console.log("Welcome post created with ID: ", docRef.id);
})
.catch((error) => {
console.error("Error creating post: ", error);
});
// ...
});
最佳答案
如 doc 中所述,serverTimestamp
返回一个哨兵,与set()
或update()
一起使用,以将服务器生成的时间戳包含在写入数据。
术语 sentinel 表示在后端计算精确值,即在将文档写入 Firestore 时在 Firestore 平台上。这就是为什么您不能将此值用于例如-Math.abs()
.
使用 serverTimestamp
代替客户端生成的时间戳值(例如 Date.now()
)的优点是该值独立于设置和时间用户计算机的区域。服务器时间将始终被考虑在内。
总而言之,你应该保持你定义的timestamp
值,删除order
字段,并且在查询时,使用.orderBy("created ", "desc")
如 Dharmaraj 的回答中所述。
关于javascript - 如何反转时间戳以在 firestore 中按最新顺序订购文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68438992/