我有一个将Cloud Firestore作为数据库的项目。现在,我想使用fetch方法更新一个文档中的数据。我的Cloud Firestore结构如下:
Logging (Collection)
[userID] (Document)
Notifications (Collection)
[notificationID] (Document)
active: "true"
type: "T1"
然后我在下面使用fetch调用:
fetch("https://firestore.googleapis.com/v1/projects/[ID]/databases/(default)/documents/Logging/[userID]
+"/Notifications/[notificationID]?updateMask.fieldPaths=active", {
method: 'PATCH',
body: JSON.stringify({
"active": "false"
}),
headers: {
Authorization: 'Bearer ' + idToken,
'Content-Type': 'application/json'
}
}).then( function(response){
console.log(response);
response.json().then(function(data){
console.log(data);
});
}).catch(error => {
console.log(error);
});
执行我正在错误提示消息中运行的提取方法
“接收到无效的JSON有效负载。'文档'的未知名称“活动”:找不到字段。”
如何使用REST API更新Firestore文档的现有字段?谁能帮我吗?我尝试了很多不同的“ URL”和方法,但是对我来说没有用。
答案 0 :(得分:2)
如Firestore REST API doc中所述,您需要在主体中传递类型为Document
的对象,如下所示:
{
method: 'PATCH',
body: JSON.stringify({
fields: {
active: {
stringValue: 'false',
},
},
}),
}
我假设您的active
字段的类型为String(因为您执行"active": "false"
)。如果它是布尔类型,则需要使用booleanValue
属性,如下所示。有关更多详细信息,请参见此doc。
{
method: 'PATCH',
body: JSON.stringify({
fields: {
active: {
booleanValue: false,
},
},
}),
}