let jobSkillsRef = db.collection('job_skills').where('job_id','==',post.job_id);
jobSkillsRef.remove();
Error Message:
jobSkillsRef.remove is not a function.
let jobSkillsRef = db.collection('job_skills').where('job_id','==',post.job_id);
jobSkillsRef.remove();
Error Message:
jobSkillsRef.remove is not a function.
If you want to delete a document, you need to have a DocumentReference
for it. Start by running the query, then iterate through the QuerySnapshot
, and finally remove each DocumentSnapshot
based on its ref
.
var job_query = db.collection('job_list').where('job_id','==',post.job_id);
job_query.get().then(function(queryResult) {
queryResult.forEach(function(doc) {
doc.ref.delete();
});
});
To efficiently handle this task, I make use of batched writes in my Firestore database implementation. Here's an example:
const jobSkillsRef = db.collection('job_skills').where('job_id', '==', post.job_id);
let batch = firestore.batch();
jobSkillsRef.get()
.then(snapshot => {
snapshot.docs.forEach(doc => {
batch.delete(doc.ref);
});
return batch.commit();
})
Alternatively, with ES6 async/await syntax:
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();
//This code snippet demonstrates how to locate and remove a document from firestore
const document = await this.noteRef.where('userId', '==', userId).get();
document.forEach(item => {
item.ref.delete();
console.log(`Document deleted: ${item.id}`);
});
One crucial element in Frank's response that resolved my issues was utilizing the .ref
within doc.ref.delete()
Initially, I only had doc.delete()
, which resulted in a "not a function" error. Now, after making this adjustment, my code appears like this and functions flawlessly:
let firestore = firebase.firestore();
let collectionReference = fs.collection(<your collection here>);
collectionReference.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);
});
give this a shot, assuming you already have the id
export const removeFile = (id) => {
return (dispatch) => {
firebase.firestore()
.collection("documents")
.doc(id)
.delete()
}
}
New possibility:
db.collection("cities").doc("DC").delete().then(function() {
console.log("Document deleted successfully!");
}).catch(function(error) {
console.error("Error while removing document: ", error);
});
To tackle this issue, I implemented a system where each document is assigned a uniqueID. By querying based on this field, I was able to retrieve the documentID of the specific document and utilize it for deletion. Here is how I accomplished this:
(Written in Swift)
func removeFriendRequest(request: Request) {
DispatchQueue.global().async {
self.db.collection("requests")
.whereField("uniqueID", isEqualTo: request.uniqueID)
.getDocuments { querySnapshot, error in
if let e = error {
print("An error occurred while fetching the document: \(e)")
} else {
self.db.collection("requests")
.document(querySnapshot!.documents.first!.documentID)
.delete() { err in
if let e = err {
print("An error occurred while deleting the document: \(e)")
} else {
print("Document successfully deleted!")
}
}
}
}
}
}
Although there may be room for improvement in the code, this method worked well for me. Hopefully, it proves useful for others facing a similar challenge in the future!
const databaseCollection = db.collection('job_skills')
var documentIds = (await databaseCollection.where("folderId", "==", folderId).get()).docs.map((document => document.id))
// delete for single result
await databaseCollection.doc(documentIds[0]).delete()
// delete for multiple results
await Promise.all(
documentIds.map(
async(docId) => await databaseCollection.doc(docId).delete()
)
)
Utilizing await/async can simplify the process:
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,
});
}
});
The need to get(), loop, and then delete() each document individually may seem cumbersome compared to executing a single SQL-style query for deletion. Despite this, Google has set the current approach as the standard.
If you find yourself utilizing Cloud Firestore from the Client side, there's a convenient solution for generating unique keys by using packages/modules like uuid. This allows you to create an ID and then assign it to the document before saving it in Firestore along with a reference on the stored object.
For instance: Suppose you wish to store a person object in Firestore; initially, you can utilize uuid to create an ID for that individual as demonstrated below.
const uuid = require('uuid')
const person = { name: "Jane Doe", age: 25}
const id = uuid() // generates a unique string ID
const personWithId = {person, id}
export const saveToFirestore = async (person) => {
await db.collection("people").doc(id).set(personWithId);
};
// To delete, retrieve the stored ID related to the object and execute the following firestore query
export const removeFromFirestore = async (id) => {
await db.collection("people").doc(id).delete();
};
This method can be beneficial for those working with Firestore on the Client side.
removeSection(section: string, subsection: string)
{
const deleteList = this.db.collection('sectionsCollection', ref => ref.where('section', '==', section).where('subsection', '==' , subsection))
deleteList.get().subscribe(itemsToDelete => itemsToDelete.forEach( doc=> doc.ref.delete()));
alert('item deleted successfully');
}
Greetings, My frontend is built on Angular 8, with a Java API service serving as the backend. I need to fetch a String from the backend, which will contain '\n' line breaks. For example: "Instructions:\n1. Key in 122<16 digit ...
How can I successfully send the following string to a spring MVC controller using ajax: (?=^.{8,}$)(?=.+\d)(?=.+[!@#$%^&]+)(?!.*[\n])(?=.+[A-Z])(?=.+[a-z])$ I am encountering a 400 bad request error and it is not leaving the client side. An ...
Currently, I am endeavoring to grasp the functioning of the Debug object in V8 for debugging javascript within an embedded-javascript C++ application. After invoking v8::Debug::SetDebugEventListener and specifying a callback function, I proceed to execute ...
Hello everyone! Currently, I'm involved in a Laravel project where I am using laravel/breeze VueJS with Inertia. The login functionality is implemented using a bootstrap modal component. While validation and authentication are working smoothly, the on ...
<el-select @change="store(types)" v-model="types" placeholder="Select"> <el-option v-for="t in types" :label="t.name" :value="t" ...
I'm currently developing a full stack application and I am facing an issue with displaying a snackbar in my signup component when the user's password and confirm password do not match. I have been advised to pass the setOpenAlert method as props ...
Is it possible to utilize a unique set of words as a seed in order to recover a lost private key, similar to how cryptocurrency wallets function? This method can be particularly beneficial for end-to-end encryption among clients, where keys are generated o ...
When a session expires, users cannot log back in without refreshing the page because the _token in ajax headers has expired (also known as TokenMismatchException). I am unable to handle this exception by redirecting users to a login page because the login ...
When looking to update a specific element in an array within a MongoDB collection. Here is an example of some MongoDB data: { _id: new ObjectId("63608e3c3b74ed27b5bdf703"), placename: "khulna", frnds: [ { name: "osama&qu ...
Currently, I am in the process of coding Selenium scripts to automate the testing of a signup procedure. In order to allow the scripts to be reused multiple times without encountering errors due to duplicated key items, I need to increment and store two v ...
I am currently working on implementing the bootstrap-vue pagination nav feature in my project. The goal is to update an ajax call with the requested page number when a new page button is clicked. Here is a snippet of my router: export default new Router( ...
I'm currently working with the Vue.js datatable. Most functionalities are operational, however, I am facing an issue where the `callmethod()` is not being executed upon clicking a button. When the button is clicked, no events seem to be triggered. Any ...
I've encountered an issue with my bootstrap date-picker and knockout integration. The problem arises when I click anywhere on my html page, as it triggers the datepicker set value action, setting the current date instead. Is there a way to prevent th ...
When the user clicks on loginAccount, the intention is to extract the text from the element with the id input-1 and assign it to username. This same process should occur for password, followed by form submission. However, despite using e.preventDefault() ...
As a newbie in JavaScript, I've been trying to find answers to my questions, but the solutions I've come across are quite complex for my level of understanding. One specific issue I'm tackling involves creating a grid of divs using user inpu ...
Error Image const isLoggedIn = true; const handleChangeEvent = () => {}; const [displayPassword, setDisplayPassword] = useState(false); const handleTogglePassword = () => setDisplayPassword((prevDisplayPassword) => !prevDi ...
Within my react project's global array for adding products, I have the following setup: const ProductContext = createContext(); export const ProductProvider = ({ children }) => { const [products, setProducts] = useState([ {brand: &ap ...
I have been attempting to override the CORS policy using the following code block: app.use('/\*', function (req, res, next) { res.header("Access-Control-Allow-Origin","*") res.header("Access-Control-Allow-Hea ...
Although I am aware that files can be imported from the same folder, I am facing a specific challenge. For example, if I have the following code: @import "mixins" .hero { @include hero } It works as expected. However, what I am attempting to do is ...
Using the egoist/vue-html plugin to render HTML works perfectly with standard HTML content, but encounters issues when trying to include a component tag. When attempting to add the Breadcrumb component in the template, it fails to work. Can anyone pinpoin ...