6 javascript firebase typescript 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});
})
Run Code Online (Sandbox Code Playgroud)
最终出现以下错误:
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>
Run Code Online (Sandbox Code Playgroud)
消息是:
Update() 需要一个单一的 JavaScript 对象或一个字段/值对的交替列表,后面可以跟一个可选的先决条件。参数“dataOrField”的值不是有效的 Firestore 文档。无法序列化“FieldValueDelegate”类型的对象(在“nComments”字段中找到)。Firestore 不支持具有自定义原型的 JavaScript 对象(即通过“new”运算符创建的对象)。
仅当我添加此“then”链时才会发生此错误:
.then(()=>{
return DocumentRef.update({nComments: increment})
})
Run Code Online (Sandbox Code Playgroud)
我不理解为什么。
只有架构的相关部分,我有 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.
Run Code Online (Sandbox Code Playgroud)
你可能使用admin的命名空间,同时使用做更新increment从firebase命名空间。尝试将您的增量语句更改为:
import * as admin from 'firebase-admin';
const increment = admin.firestore.FieldValue.increment(1);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
784 次 |
| 最近记录: |