javascript - 如何反转时间戳以在 firestore 中按最新顺序订购文档

标签 javascript node.js firebase google-cloud-firestore google-cloud-functions

((已解决))

希望获得一些帮助来解决这个问题,首先我是 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/

相关文章:

javascript - Jest 收到 : serializes to the same string

javascript - Three.js 使用 Node 模块的路径

javascript - react Hook : What is the disadvantage of directly changing the nested object?

php - JavaScript 未加载。尝试了我能想到的一切

javascript - 将小数延迟传递给 setInterval 或 setTimeout 是否安全?

node.js - 防止 sequelize 在 node.js 应用程序中删除数据库

java - 无法在 Firebase 上初始化类 FirebaseThreadManagers 错误

firebase - 没有 Google 帐户的应用程序用户是否可以使用 Firebase?

typescript 接口(interface)变量空检查并设置默认值

javascript - 关闭(好方法书)