使用动态键从 Firestore 删除字段

问题描述 投票:0回答:2

我正在尝试从 Firestore 中的文档中删除单个字段 该字段的键保存在变量中,例如

var userId = "random-id-1"

在文档中,我的成员字段结构如下:

{
  members:{
    random-id-1:true,
    random-id-2:true
  }
}

我想删除

random-id-1:true
,但保留
random-id-2:true

如果不获取整个成员对象并编写更新的对象,这怎么可能?

我已经尝试过this,但是我收到错误:

Document references must have an even number of segments

我也尝试过这个:

db.collection('groups').doc(this.props.groupId).set({
  members: {
    [userId]: firebase.firestore.FieldValue.delete()
  }
},{merge: true})

但是我收到错误:

Function DocumentReference.update() called with invalid data. FieldValue.delete() can only appear at the top level of your update data

感谢您的帮助

javascript firebase google-cloud-firestore
2个回答
43
投票

我已经成功删除了这样的字段:

let userId = "this-is-my-user-id"
let groupId = "this-is-my-group-id"

db.collection('groups').doc(groupId).update({
  ['members.' + userId]: firebase.firestore.FieldValue.delete()
})

这是使用这里

描述的点运算符方法

如果有其他方法请告诉我

谢谢


8
投票

这里是[删除字段的文档](来自文档:https://firebase.google.com/docs/firestore/manage-data/delete-data#fields)。

对于 Node.js,请确保导入 FieldValue。

// Get the `FieldValue` object
const FieldValue = require('firebase-admin').firestore.FieldValue;
            
// Create a document reference
const cityRef = db.collection('cities').doc('BJ');
            
// Remove the 'capital' field from the document
const removeCapital = cityRef.update({
  capital: FieldValue.delete()
});

如果您使用的是 Web 模块化 API,请尝试:

import { doc, updateDoc, deleteField } from "firebase/firestore";

const cityRef = doc(db, 'cities', 'BJ');

// Remove the 'capital' field from the document
await updateDoc(cityRef, {
    capital: deleteField()
});
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.