【问题标题】:Why does Firebase timestamp object return undefined?为什么 Firebase 时间戳对象返回未定义?
【发布时间】:2019-11-30 02:53:57
【问题描述】:

我正在做一些测试以进入 Firebase。但是现在当我尝试访问我的时间戳对象时,它返回未定义。

这是我尝试注销日期的数组项(配方)之一的示例,从控制台复制:

{author: "xan", created at: n, title: "awesome test"}
 author: "xan"
 created at: n
 nanoseconds: 0
 seconds: 1563660000
__proto__:
  isEqual: ƒ (t)
  toDate: ƒ ()
  toMillis: ƒ ()
  toString: ƒ ()
  _compareTo: ƒ (t)
  constructor: ƒ n(t,e)
  __proto__: Object

这是我的代码:

const list = document.querySelector('ul');

const addRecipe = (recipe) => {
  let time = recipe.created_at.toDate();
  console.log(recipe.created_at);  // returns undefined ??
  let html = `
    <li>
      <div>${recipe.title}</div>
      <div>${time}</div>
    </li>
  `;

  list.innerHTML += html;
}

db.collection('recipes').get().then(snapshot => {
  snapshot.docs.forEach(doc => {
    addRecipe(doc.data());
  });
}).catch(err => {
  console.log(err);
});

为什么recipe.created_at 返回未定义?

【问题讨论】:

  • 在第一个代码块中,您使用的是created at,作为响应,您正在检查created_at。尝试直接console.log(recipe)

标签: javascript firebase google-cloud-firestore nosql timestamp


【解决方案1】:

看起来您的数据库字段被称为“created at”,单词之间有一个空格,但您希望它是“created_at”,单词之间有一个下划线。确保读取文档的代码也与写入文档的代码匹配。

【讨论】:

  • 我创建了一个名称中没有空格的新时间戳。那解决了它。谢谢! (它被命名为“created at”的原因是我在一个示例中看到过它,并且在代码中通过“created_at”调用它似乎是有效的。)
猜你喜欢
  • 2021-11-10
  • 1970-01-01
  • 2020-01-05
  • 1970-01-01
  • 2019-01-21
  • 2012-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多