![](/img/trans.png)
[英]FLUTTER: How to delete multiple documents using where clause in cloud firestore?
[英]How to delete document from firestore using where clause
var jobskill_ref = db.collection('job_skills').where('job_id','==',post.job_id);
jobskill_ref.delete();
抛出错误
jobskill_ref.delete 不是 function
只有拥有DocumentReference
才能删除文档。 为此,您必须首先执行查询,然后遍历QuerySnapshot
,最后根据其ref
删除每个DocumentSnapshot
。
var jobskill_query = db.collection('job_skills').where('job_id','==',post.job_id);
jobskill_query.get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
doc.ref.delete();
});
});
我为此使用批量写入。 例如:
var jobskill_ref = db.collection('job_skills').where('job_id','==',post.job_id);
let batch = firestore.batch();
jobskill_ref
.get()
.then(snapshot => {
snapshot.docs.forEach(doc => {
batch.delete(doc.ref);
});
return batch.commit();
})
ES6 异步/等待:
const jobskills = await store
.collection('job_skills')
.where('job_id', '==', post.job_id)
.get();
const batch = store.batch();
jobskills.forEach(doc => {
batch.delete(doc.ref);
});
await batch.commit();
//The following code will find and delete the document from firestore
const doc = await this.noteRef.where('userId', '==', userId).get();
doc.forEach(element => {
element.ref.delete();
console.log(`deleted: ${element.id}`);
});
弗兰克的回答是固定我的问题是关键部分.ref
在doc.ref.delete()
我最初只有doc.delete()
给出了“不是函数”错误。 现在我的代码看起来像这样并且完美运行:
let fs = firebase.firestore();
let collectionRef = fs.collection(<your collection here>);
collectionRef.where("name", "==", name)
.get()
.then(querySnapshot => {
querySnapshot.forEach((doc) => {
doc.ref.delete().then(() => {
console.log("Document successfully deleted!");
}).catch(function(error) {
console.error("Error removing document: ", error);
});
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
当然,您可以使用 await/async:
exports.delete = functions.https.onRequest(async (req, res) => {
try {
var jobskill_ref = db.collection('job_skills').where('job_id','==',post.job_id).get();
jobskill_ref.forEach((doc) => {
doc.ref.delete();
});
} catch (error) {
return res.json({
status: 'error', msg: 'Error while deleting', data: error,
});
}
});
我不知道为什么你必须get()它们并循环它们,然后delete()它们,而你可以像任何 SQL 语句一样准备一个查询,在一个步骤中删除哪里,但谷歌决定这样做。 所以,就目前而言,这是唯一的选择。
delete(seccion: string, subseccion: string)
{
const deletlist = this.db.collection('seccionesclass', ref => ref.where('seccion', '==', seccion).where('subseccion', '==' , subseccion))
deletlist.get().subscribe(delitems => delitems.forEach( doc=> doc.ref.delete()));
alert('record erased');
}
如果您在客户端使用 Cloud Firestore,则可以使用像 uuid 这样的唯一密钥生成器包/模块来生成 ID。 然后将文档的 ID 设置为从 uuid 生成的 ID,并在 Firestore 中存储的对象上存储对该 ID 的引用。
例如:如果您想将一个人对象保存到 Firestore,首先,您将使用 uuid 为该人生成一个 ID,然后保存如下。
const uuid = require('uuid')
const person = { name: "Adebola Adeniran", age: 19}
const id = uuid() //generates a unique random ID of type string
const personObjWithId = {person, id}
export const sendToFireStore = async (person) => {
await db.collection("people").doc(id).set(personObjWithId);
};
// To delete, get the ID you've stored with the object and call // the following firestore query
export const deleteFromFireStore = async (id) => {
await db.collection("people").doc(id).delete();
};
希望这可以帮助任何在客户端使用 firestore 的人。
你现在可以这样做:
db.collection("cities").doc("DC").delete().then(function() {
console.log("Document successfully deleted!");
}).catch(function(error) {
console.error("Error removing document: ", error);
});
我解决这个问题的方法是给每个文档一个 uniqueID,在该字段上查询,获取返回文档的 documentID,并在删除中使用它。 像这样:
(迅速)
func rejectFriendRequest(request: Request) {
DispatchQueue.global().async {
self.db.collection("requests")
.whereField("uniqueID", isEqualTo: request.uniqueID)
.getDocuments { querySnapshot, error in
if let e = error {
print("There was an error fetching that document: \(e)")
} else {
self.db.collection("requests")
.document(querySnapshot!.documents.first!.documentID)
.delete() { err in
if let e = err {
print("There was an error deleting that document: \(e)")
} else {
print("Document successfully deleted!")
}
}
}
}
}
}
代码可以稍微清理一下,但这是我想出的解决方案。 希望它可以在未来帮助某人!
或者试试这个,但你必须事先有 id
export const deleteDocument = (id) => {
return (dispatch) => {
firebase.firestore()
.collection("contracts")
.doc(id)
.delete()
}
}
Kotlin 的代码,包括失败侦听器(用于查询和删除每个文档):
fun deleteJobs(jobId: String) {
db.collection("jobs").whereEqualTo("job_id", jobId).get()
.addOnSuccessListener { documentSnapshots ->
for (documentSnapshot in documentSnapshots)
documentSnapshot.reference.delete().addOnFailureListener { e ->
Log.e(TAG, "deleteJobs: failed to delete document ${documentSnapshot.reference.id}", e)
}
}.addOnFailureListener { e ->
Log.e(TAG, "deleteJobs: query failed", e)
}
}
感谢您为 Stack Overflow 提供答案!
请务必回答问题。 提供详细信息并分享您的研究!
但避免...
寻求帮助、澄清或回应其他答案。根据意见发表声明; 用参考资料或个人资料备份它们
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.