【发布时间】:2021-09-21 05:18:08
【问题描述】:
您好,我试图从我的集合中删除一个特定文档,因为虽然我知道删除集合中具有特定 ID 的文档的代码(我正在阅读:Delete data from Cloud Firestore),显然我错了,很高兴它是一个测试集合。
所以我的问题是如何使用特定 ID 从集合中删除文档 首先这是我在我的集合中存储数据的方式:
const register = (e) => {
e.preventDefault();
const docId = `${descripcion}`;
const docRef = db.collection('productosAIB').doc(docId);
docRef.get().then((doc) => {
if (doc.exists)
{
window.alert("Ya existe ese producto")
}
else {
docRef.set({
descripcion: descripcion,
grado: grado,
precio: precio,
cantidad: cantidad,
id: docRef.id
}).then((r) => {
window.alert("Producto agregado")
})}
})
}
所以我创建了一个名为 docID 的变量,它将获取用户可以通过输入发送的描述然后我确保创建的文档将是 doc.id 然后我将所有信息发送到数据库,这是最终结果:
- 所有数据都是用户先插入的
- 这就是它在 Firestore 中更新后的样子
- 这是它在表格中的样子:
现在我创建了一个名为 deleteProduct 的函数,该函数旨在删除文档而不是整个集合:
const deleteProduct = (producto) => {
db.collection("productosAIB").doc(producto).delete();
}
这是渲染/打印表格和调用函数的地方 (注意:该函数在“”(引号)上,因为我不希望该函数运行,因为它会删除我刚刚创建的文档)
<tbody>
{productos.map((productos, index) => (
<tr key={productos.id || index}>
<td>
<input className = "agregarAIB_cantidad"
onChange = {(e) => {changeCantidad(productos.descripcion, e.target.valueAsNumber)}}
type = 'number'
pattern = "[0-9]*"
required
value = {productos.cantidad}
/>
</td>
<td>{productos.grado}</td>
<td >
{productos.descripcion}
</td>
<td >$
<input className = "agregarAIB_precio"
onChange = {(e) => {changePrecio(productos.descripcion, e.target.valueAsNumber)}}
type = 'number'
pattern = "[0-9]*"
required
value = {productos.precio}
/>
</td>
<th>
<button onClick = "{deleteProduct(productos.descripcion)}"/> <-- This is the function
</th>
</tr>
))
}
</tbody>
现在奇怪的是(这就是我来这里询问的原因)是我什至没有单击按钮并运行了该功能(这就是为什么我现在将它放在引号中),这是因为在地图什么的?因为它对我来说没有任何意义,因为某种原因,它在不点击显示“OnClick”的按钮的情况下运行。
欢迎任何提示、文档和帮助,如果需要完整代码,请告诉我。
【问题讨论】:
标签: javascript reactjs google-cloud-firestore