【问题标题】:Cloud Firestore document add gives error "Value for argument "data" is not a valid Firestore document. Cannot use "undefined" as a Firestore value"Cloud Firestore 文档添加给出错误“参数“数据”的值不是有效的 Firestore 文档。不能使用“未定义”作为 Firestore 值”
【发布时间】:2020-01-16 12:53:56
【问题描述】:

我正在做一个 react 项目,这是我的第一个 react 项目。此代码已成功部署。但是在使用邮递员进行测试时会出现一些错误。我“发布”“createScream”函数的 URL 并发送它。然后我得到了这个错误。

非常感谢您对解决问题的任何帮助。我是反应世界的新手。这是我的 index.json 文件

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
 exports.helloWorld = functions.https.onRequest((request, response) => {
  response.send("Hello world");
 });

 exports.getScreams = functions.https.onRequest((req, res)=> {
     admin
     .firestore()
     .collection('screams')
     .get()
     .then(data=>{
         let screams =[];
         data.forEach(doc =>{
             screams.push(doc.data());
         });
         return res.json(screams);
     })
     .catch((err)=> console.error(err));
 });

 exports.createScream = functions.https.onRequest((req, res)=> {
    const newScream = {
        body:req.body.body,
        userHandle: req.body.userHandle,
        createdAt: admin.firestore.Timestamp.fromDate(new Date())
    };

    admin
    .firestore()
    .collection('screams')
    .add(newScream)
    .then((doc)=>{
        res.json({message:'document ${doc.id} created successfully'});
    })
    .catch((err)=>{
        res.status(500).json({ error:'something went wrong'});
        console.error(err);

    });

我收到此错误消息

Error: Value for argument "data" is not a valid Firestore document. Cannot use "undefined" as a Firestore value (found in field body).
    at Object.validateUserInput (E:\survival\TF2\functions\node_modules\@google-cloud\firestore\build\src\serializer.js: 273: 15)
    at Object.validateDocumentData (E:\survival\TF2\functions\node_modules\@google-cloud\firestore\build\src\write-batch.js: 611: 22)
    at CollectionReference.add (E:\survival\TF2\functions\node_modules\@google-cloud\firestore\build\src\reference.js: 1765: 23)
    at exports.createScream.functions.https.onRequest (E:\survival\TF2\functions\index.js: 38: 6)
    at Run (C:\Users\User\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js: 608: 20)
    at C:\Users\User\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js: 582: 19
    at Generator.next (<anonymous>)
    at C:\Users\User\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js: 7: 71
    at new Promise (<anonymous>)
    at __awaiter (C:\Users\User\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js: 3: 12)

【问题讨论】:

  • 欢迎来到 StackOverflow!也许阅读thisthis :)
  • 错误提示您正在发送和undefined 值。您可以在 POST 中粘贴您发送的正文吗?
  • 只要确保在通过邮递员发送请求时添加 Content-Type:application/json 标头
  • 如果您使用 Postman 发出请求,则不清楚这与 React 有何关系。
  • @ErandiDilshani 它与 firebase.json 无关 :) 。我说的是邮递员。您需要指定 Content-Type:application/json 标头 learning.getpostman.com/docs/postman/sending_api_requests/…

标签: javascript firebase google-cloud-functions postman


【解决方案1】:

问题在于这段代码:

const newScream = {
    body:req.body.body,
    userHandle: req.body.userHandle,
    createdAt: admin.firestore.Timestamp.fromDate(new Date())
};

admin
.firestore()
.collection('screams')
.add(newScream)

当您尝试将文档添加到其中一个属性值为 undefined 的 Cloud Firestore 时,您将收到此错误。这意味着newScream 上的三个属性中至少有一个是未定义的。错误信息告诉你是哪一个:

不能将“未定义”用作 Firestore 值(在字段正文中找到)

所以,body 属性是未定义的。您需要调试您的函数并找出为什么 req.body.body 未定义。也许客户端没有传递那个值。

【讨论】:

  • 这应该被标记为正确答案。就我而言,我有一个未定义的 ID。我想还有一种忽略未定义值的新方法,因为错误消息现在显示“如果您想忽略未定义值,请启用ignoreUndefinedProperties。”但是在哪里甚至可以启用此功能?
  • 太棒了!谢谢。至少可以说,错误消息非常不清楚......
【解决方案2】:

我正在从事与您工作相同的项目。我遇到了同样的错误,只需重写 createdScream 代码,重新启动邮递员并创建新的 POST 请求。 然后发送新的请求。这行得通。

【讨论】:

    【解决方案3】:

    确保在使用 postman 更改为 POST 方法时,在 url 下方的 body 部分,单击 raw 选项,然后在最有可能显示 Text 的下拉列表中,将其更改为 JSON。

    【讨论】:

    • 对我来说,我在 BODY 选项卡下将“raw”更改为“x-www-form-urlencoded”,它起作用了。在此之前,我试图从 Params 部分而不是 Body 部分发布。
    【解决方案4】:

    我也遇到过这个问题。

    原来我犯的错误是在

    const newScream = {
        body:req.body.body,
        userHandle: req.body.userHandle,
        createdAt: admin.firestore.Timestamp.fromDate(new Date())
    };
    

    req.body.userHandle 中的 userHandle 在邮递员 json 中具有小写 user

    {
      'body':'new',
      'UserHandle': 'new'
    }
    

    发出的请求有UserHandle大写。

    我通过将 js 中的 userHandle: req.body.userHandle 更改为大写来解决此问题 UserHandle: req.body.UserHandle.

    确保const newScream 中的任何内容与您尝试在邮递员 json 中发送的内容完全匹配。

    【讨论】:

      【解决方案5】:

      我有同样的问题,我通过在 Postman 的方法“POST”的正文中选择“x-www-form-urlencoded”找到了另一个替代解决方案。修改键和值然后发送。

      【讨论】:

        【解决方案6】:

        我的问题是使用 userHandle,而在用户中我使用的是 handle。我刚刚将尖叫帖子中的值从 userHandle 重命名为 just handle,见下文:

        之前

        const newScream = {
          body: req.body.body,
          userHandle: req.user.userHandle,
          createdAt: new Date().toISOString(),
        };
        

        修正后

        const newScream = {
          body: req.body.body,
          userHandle: req.user.handle,
          createdAt: new Date().toISOString(),
        };
        

        【讨论】:

          【解决方案7】:

          我也尝试使用相同的编码并解决了问题。

          在邮递员中,您会看到错误Cannot use "undefined" as a Firestore value (found in field body).,但没关系。因为它在您的帖子 URL 中没有任何数据。

          您可能会被误认为是在屏幕上看到的。点击网址输入处下方的body tag。然后选择raw。最后切换到 JSON,您的问题将得到解决。 将JSON数据写入下图中红线处。

          然后,写入 JSON 数据后,按下[send],您将能够在屏幕下方看到message :~~ successfully

          试试吧!

          【讨论】:

            【解决方案8】:

            Postman Image

            所以,我只是做了 firebase deploy,而不是 firebase serve,一切正常,我可以添加 newScream。 p>

            【讨论】:

              【解决方案9】:

              确保您在邮递员中使用正确的端点

              每个 firebase 函数都应该有一个唯一的端点

              例如: 对于getScreams 函数,你有一个链接

              https://us-central1-chat-app-xmx.cloudfunctions.net/getScreams
              

              对于createScreams 函数,您将有另一个链接,例如:

              https://us-central1-chat-app-xmx.cloudfunctions.net/createScreams
              

              现在你应该在邮递员中使用post request 的链接是createScreams endpoint 和get request 你需要使用getScreams 端点

              您得到的错误不是什么大问题,因为该过程需要客户端输入一些数据,但您需要使用正确的端点将您的文档成功发送到 firestore

              【讨论】:

                【解决方案10】:

                检查以确保在 Postman 或您使用的任何其他 API 中选择了 JSON(application/json)。

                【讨论】:

                  【解决方案11】:

                  对我来说,解决问题的方法是修复在 post 请求中赋予 createdAt 属性的值。通过为_seconds_nanoseconds 赋值:

                  "createdAt":{"_seconds":1623472200,"_nanoseconds":0},

                  而不仅仅是给出时间价值

                  "createdAt": "10:00pm",

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2020-04-25
                    • 2021-03-25
                    • 1970-01-01
                    • 2018-04-12
                    • 1970-01-01
                    • 2021-05-30
                    相关资源
                    最近更新 更多