使用firestore.FieldValue.increment(1)时如何解决错误“参数“ dataOrField”的值不是有效的Firestore文档”?

时间:2020-08-03 15:41:34

标签: javascript typescript firebase google-cloud-firestore

我正在执行一个简单的操作,即试图增加一个字段的计数。代码如下:

import * as firebase from 'firebase';

const DocumentRef = db.doc(`pages/${request.params.pageId}`);

const increment = firebase.firestore.FieldValue.increment(1);

DocumentRef
    .get()
    .then(function (documentSnapshot) {
        if(!documentSnapshot.exists){
            return response.status(404).json({"message":"page not found"})
        }else{
            return db.collection(`comments`).add(newComment)
        }
    })
    .then(()=>{
        return DocumentRef.update({nComments: increment})
    })
    .then(() => {
        response.status(200).json(newComment);
    })
    .catch((error) => {
        console.log(error)
        return response.status(500).json({message:error.code});
    })

最终出现以下错误:

Error: Update() requires either a single JavaScript object or an alternating list of field/value pairs that can be followed by an optional precondition. Value for argument "dataOrField" is not a valid Firestore document. Couldn't serialize object of type "FieldValueDelegate" (found in field "nComments"). Firestore doesn't support JavaScript objects with custom prototypes (i.e. objects that were created via the "new" operator).
    at WriteBatch.update (/srv/node_modules/@google-cloud/firestore/build/src/write-batch.js:374:23)
    at DocumentReference.update (/srv/node_modules/@google-cloud/firestore/build/src/reference.js:377:14)
    at screamDocumentRef.get.then.then (/srv/lib/handlers/screams.js:105:34)
    at <anonymous> 

消息是:

Update()需要单个JavaScript对象或字段/值对的交替列表,其后可以有一个可选的前提条件。参数“ dataOrField”的值不是有效的Firestore文档。无法序列化“ FieldValueDelegate”类型的对象(在字段“ nComments”中找到)。 Firestore不支持带有自定义原型的JavaScript对象(即通过“ new”运算符创建的对象)。

仅当我添加此“ then”链时才会发生此错误:

.then(()=>{
        return DocumentRef.update({nComments: increment})
    })

我不明白为什么。

仅是架构的相关部分,我有2个集合。

   collection: pages(nComments, body, etc)    id: pageId 
   collection: comments(pageId, etc)          id: commentId

when new comment document is added in comments collection, Im updating the count in pages collections document whose pageId is in comment documents pageId field.

nComments and pageId are fields.

1 个答案:

答案 0 :(得分:2)

您可能在使用admin名称空间中的increment时使用firebase名称空间进行更新。尝试将您的增量声明更改为:

import * as admin from 'firebase-admin';
const increment = admin.firestore.FieldValue.increment(1);
相关问题