【问题标题】:Firestore addDoc not storing whole objectFirestore addDoc 不存储整个对象
【发布时间】:2022-02-15 04:30:21
【问题描述】:

您好,我在调用 addDoc 传递对象(useState Hook)时遇到了 firebase 问题。

问题是有时对象与所有字段一起存储,有时则不存储(传递相同的数据)

让我把你放在上下文中。这是我最初声明对象的方式:

const [trade, setTrade] = useState({
  ticker: "",
  units: "",
  price: "",
  result_balance: "",
  createdAt: todaysDate,
  direction: "",
  status: true,
  cprice: "",
  closedAt:"",
});

这是我调用 addDoc 以将数据保存到 firestore 的函数:

const saveTrade = async (e) => {

  trade.createdAt = todaysDate;
  trade.ticker = trade.ticker.toUpperCase()

  if(trade.cprice){
    trade.closedAt =todaysDate;
  }
  try {
    await addDoc(
      collection(
        db,
        "journals",
        window.location.pathname.replace("/journal", ""),
        "entries"
      ),
      trade. //Passing the object here
    );
  } catch (e) {
    console.log(e);
  }

  
  setTrade({});
  closeHandler();
};

正如我所说,它有时会正确存储对象:Good scenario

但有时不是Bad scenario (not all the fields created in firestore)

希望有人可以就如何解决这个问题给我建议或提示。

【问题讨论】:

  • 也许它设置为忽略未定义的值?在那种情况下它不会写。

标签: reactjs google-cloud-firestore next.js


【解决方案1】:

看到其他人的代码后,我意识到我错误地调用了setTrade({}) 以清除字段。现在我这样称呼它:

 const saveTrade = async (e) => {

  trade.createdAt = todaysDate;
  trade.ticker = trade.ticker.toUpperCase()

  if(trade.cprice){
    trade.closedAt =todaysDate;
  }
  try {
    await addDoc(
      collection(
        db,
        "journals",
        window.location.pathname.replace("/journal", ""),
        "entries"
      ),
      trade. //Passing the object here
    );
  } catch (e) {
    console.log(e);
  }

  
  setTrade({
   ticker: "",
   units: "",
   price: "",
   result_balance: "",
   createdAt: todaysDate,
   direction: "",
   status: true,
   cprice: "",
   closedAt:"",
   });
  closeHandler();
};

现在可以完美运行了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 2023-01-04
    • 2019-07-06
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    相关资源
    最近更新 更多