简体   繁体   English

Cloud Firestore 文档添加给出错误“参数“数据”的值不是有效的 Firestore 文档。不能使用“未定义”作为 Firestore 值”

[英]Cloud Firestore document add gives error "Value for argument "data" is not a valid Firestore document. Cannot use "undefined" as a Firestore value"

I'm working on a react project and this is my very first react project.我正在做一个反应项目,这是我的第一个反应项目。 This code is deployed successfully.此代码已成功部署。 But get some errors while testing with postman.但是在使用 postman 进行测试时会出现一些错误。 I "post" the "createScream" functions's URL and send it.我“发布”“createScream”函数的 URL 并发送。 then I got this errors.然后我得到了这个错误。

Any help towards resolution is highly appreciated.任何对解决问题的帮助都非常感谢。 I'm new to react world.我是反应世界的新手。 Here's my index.json file这是我的 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);

    });

I got this error message我收到此错误消息

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)

The problem is with this code:问题在于这段代码:

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

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

When you try to add a document to Cloud Firestore where one of the property values is undefined , you will get this error.当您尝试向 Cloud Firestore 添加属性值之一为undefined的文档时,您将收到此错误。 This means that at least one of the three properties on newScream is undefined.这意味着newScream的三个属性中至少有一个是未定义的。 The error message is telling you which one:错误消息告诉您是哪一个:

Cannot use "undefined" as a Firestore value (found in field body)不能使用“未定义”作为 Firestore 值(在字段正文中找到)

So, the body property is undefined.因此,body 属性是未定义的。 You'll need to debug your function and figure out why req.body.body is undefined.您需要调试您的函数并找出req.body.body未定义的原因。 Perhaps the client isn't passing that value.也许客户端没有传递该值。

Make sure when using postman to change to POST method, On the body section underneath the url, click on the raw option, and on the dropdown that most likely says Text, change it to JSON.确保在使用邮递员更改为 POST 方法时,在 url 下方的正文部分,单击原始选项,然后在最有可能显示文本的下拉列表中,将其更改为 JSON。 在此处输入图片说明

The problem for my case was using userHandle , while in the users i had used handle .我的情况的问题是使用userHandle ,而在用户中我使用了handle I just renamed the value in scream post from userHandle to just handle, see below:我刚刚将尖叫帖子中的值从 userHandle 重命名为 just handle,见下文:

Before

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

After Correction修正后

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

I also try to the same coding and I solved the problem.我也尝试相同的编码,我解决了这个问题。

In postman, you will see the error Cannot use "undefined" as a Firestore value (found in field body).在邮递员中,您将看到错误Cannot use "undefined" as a Firestore value (found in field body). but it's Ok.但没关系。 Because it doesn't have any data in your post URL.因为它在您的帖子 URL 中没有任何数据。

You may be mistaken for the screen to see.你可能会误以为是屏幕看到的。 Click the body tag under the URL input place.单击 URL 输入位置下的body tag Then select raw .然后选择raw Finally switch to JSON and your problem will be solved.最后切换到JSON,您的问题将得到解决。 Write the JSON data in the red line in the picture below.将JSON数据写入下图红线。

And Then, after writing the JSON data and you press [send] , you will be able to see message :~~ successfully at the under screen.然后,在写入 JSON 数据并按[send] ,您将能够在屏幕下方message :~~ successfully看到message :~~ successfully

Try it!尝试一下!

在此处输入图片说明

To solve this issue, use the ignoreUndefinedProperties setting on the Firestore instance.要解决此问题,请在 Firestore 实例上使用ignoreUndefinedProperties设置

This skips undefined properties during serialization so that they don't get written into the Firestore document in the first place:这会在序列化期间跳过未定义的属性,以便它们不会首先写入 Firestore 文档:

import * as admin from 'firebase-admin';

admin.initializeApp();

const firestore = admin.firestore();
firestore.settings({ ignoreUndefinedProperties: true });
const doc = firestore.doc(`demo`);
doc.create({ id: 1, description: undefined }); // works without exception

In my case, I sent the request from postman as raw data, changing the data type to json made it work!就我而言,我将来自postman的请求作为原始数据发送,将数据类型更改为json使其工作!

I am working on same project that you worked.我正在做你工作的同一个项目。 i got same error and just rewrite createdScream code, relaunch postman and create new POST request.我遇到了同样的错误,只是重写了 createdScream 代码,重新启动邮递员并创建新的 POST 请求。 Then send new request.然后发送新的请求。 That works.那个有效。

I've had this problem as well.我也遇到过这个问题。

It turns out the mistake I made was that in原来我犯的错误是在

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

The userHandle in req.body.userHandle has lowercase user while in postman json userHandle中的userHandlereq.body.userHandle json 中有小写user

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

the request sending out has UserHandle uppercase.发出的请求有UserHandle大写。

I fixed the issue by changing userHandle: req.body.userHandle in js to uppercase UserHandle: req.body.UserHandle .我通过改变固定的问题userHandle: req.body.userHandle在JS为大写UserHandle: req.body.UserHandle

Make sure whatever in const newScream matches exactly what you are trying to send out in postman json.确保const newScream中的任何const newScream与您尝试在const newScream json 中发送的内容完全匹配。

I have the same problem and I found another alternative solution by selecting 'x-www-form-urlencoded' in Body of the method 'POST' in Postman.我有同样的问题,我通过在 Postman 的方法“POST”的正文中选择“x-www-form-urlencoded”找到了另一个替代解决方案。 Modify the keys and values then send.修改键和值然后发送。

Postman Image邮递员图片

So, I just did firebase deploy , instead of firebase serve and everything worked fine & I was able to add newScream.所以,我只是做了firebase deploy ,而不是firebase serve ,一切正常,我能够添加 newScream 。

make sure that you are using the right endpoint in postman确保您在邮递员中使用了正确的端点

for every firebase function there should be a unique endpoint对于每个 firebase 函数都应该有一个唯一的端点

for example: for getScreams function, you have a link例如:对于getScreams函数,您有一个链接

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

for createScreams functions you will have another link, for example:对于createScreams函数,您将有另一个链接,例如:

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

Now the link you should use in postman for post request is createScreams endpoint and for get request you need to use getScreams endpoint现在,您应该在邮递员中用于post request的链接是createScreams端点,对于get request您需要使用getScreams端点

The error you get is not a big deal because the process need a client to enter some data, but you need to use the right endpoint to send your document successfully to firestore您得到的错误不是什么大问题,因为该过程需要客户端输入一些数据,但是您需要使用正确的端点才能将您的文档成功发送到 firestore

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

For me what solved the problem was fixing the value given to the createdAt property in post request.对我来说,解决问题的方法是修复 post 请求中给createdAt属性的值。 By giving values to both _seconds and _nanoseconds :通过给_seconds_nanoseconds

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

instead of just giving time value而不是仅仅给予时间价值

"createdAt": "10:00pm", "createdAt": "10:00pm",

Undefined is not an acceptable value in Firestore. Undefined 在 Firestore 中不是可接受的值。 And the data you are setting needs to be an object {} not an array []您设置的数据需要是 object {}而不是数组[]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM