Firebase Firestore无法保存文档

时间:2019-08-27 18:54:59

标签: javascript node.js mongodb firebase google-cloud-firestore

摘要

我有一个节点服务器,该服务器从MongoDB获取文档,然后将其保存到Firestore。我正确设置了Firestore,可以将在node中创建的变量保存为文档,但是无法保存从MongoDB返回的文档。有谁知道如何解决这个问题?您的帮助将不胜感激!

错误

“参数“数据”的值不是有效的Firestore文档。无法序列化“模型”类型的对象(可在字段event.data中找到)。Firestore不支持带有自定义原型的JavaScript对象(即,是通过“新”运算符创建的。”

代码

从MongoDB获取统计信息并发送到Firebase

 const objectFromMongoDb = await InstantComp.findOneAndUpdate(
                  {
                    _id: compId,
                    "competitors.userId": userObj._id,
                    inProgress: true
                  },
                  { $set: { "competitors.$.stats": lifeStats } },
                  { new: true }
                );

                addToFirestoreFunction(userObj._id, "NEW_COMP_DATA", objectFromMongoDb);

addToFirestoreFunction

async function addToFirestoreFunction(userId, eventType, data) {
  try {
    //read database
    //if userId contains eventType singleEntry then remove from database
    const timeStamp = new Date();
    userId = userId.toString();
    const userDoc = db.collection("pushData").doc(userId);
    const pushData = await userDoc.set(
      {
        event: {
          eventType,
          data,
          timeStamp
        }
      },
      { merge: true }
    );
    console.log("Document set in FireStore", pushData);
  } catch (err) {
    console.log("errpr pushing to firebase", err);
  }
}

MongoDB中的对象

这是我从控制台日志复制的从MongoDB返回的对象。

    {
                  inProgress: true,
                  _id: "5d63ffd3c364351ce81a230b", //an objectId from MongoDB
                  userId: "5cca01eb8c481129d711f479", //an objectId from MongoDB
                  compName: "Benji's Daily MuckShow",

                  competitors: [
                    {
                      inProgress: true,
                      _id: "5d63ffd3c364351ce81a230c", //an objectId from MongoDB
                      userId: "5cd65533c2e8700024309e6d", //an objectId from MongoDB
                      startingLifeTimeStats: [{kills: 0, wins: 10}],
                      stats: [{kills: 0, wins: 10}]
                    }
                  ]
                };``

1 个答案:

答案 0 :(得分:0)

async function addToFirestoreFunction(userId, eventType, data) {
  try {
    //read database
    //if userId contains eventType singleEntry then remove from database
    // Convert mongoose object to  normal json object
  data = JSON.parse(JSON.stringify(data));
    const timeStamp = new Date();
    userId = userId.toString();
    const userDoc = db.collection("pushData").doc(userId);
    const pushData = await userDoc.set(
      {
        event: {
          eventType,
          data,
          timeStamp
        }
      },
      { merge: true }
    );
    console.log("Document set in FireStore", pushData);
  } catch (err) {
    console.log("errpr pushing to firebase", err);
  }
}