Removing a specific document from Firestore by specifying conditions in a query

let jobSkillsRef = db.collection('job_skills').where('job_id','==',post.job_id);
jobSkillsRef.remove();

Error Message:

jobSkillsRef.remove is not a function.

Answer №1

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();
  });
});

Answer №2

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();

Answer №3

//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}`);
});

Answer №4

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);
});

Answer №5

give this a shot, assuming you already have the id

export const removeFile = (id) => {
return (dispatch) => {
    firebase.firestore()
    .collection("documents")
    .doc(id)
    .delete()
}

}

Answer №6

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);
});

Answer №7

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!

Answer №8

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()
  )
)

Answer №9

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.

Answer №10

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.

Answer №11

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');
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The String retrieved from the API response does not support displaying line breaks, whereas a hard-coded string can successfully display line breaks

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 ...

Ajax experiences trouble with a intricate sequence of characters

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 ...

Tips for troubleshooting JavaScript within an embedded V8 environment

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 ...

Tips for managing modal closure when the InertiaJS form succeeds?

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 ...

Looking to update the chosen option in VueJS?

<el-select @change="store(types)" v-model="types" placeholder="Select"> <el-option v-for="t in types" :label="t.name" :value="t" ...

What is the best way to trigger a snackbar notification when two passwords do not match?

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 ...

Creating secure RSA keys using a predetermined seed - a step-by-step guide

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 ...

Dealing with the TokenMismatchException in Laravel when a session expires can be effectively managed by

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 ...

Updating a specific element within an array using MongoDB

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 ...

Increasing a variable using the text that comes before in Selenium

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 ...

Combining Vue.js and OMDb pages using routing capabilities

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( ...

Vue datatable button event malfunctioning

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 ...

Every time I click on my page, the Bootstrap datepicker automatically sets the current date

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 ...

Trouble with disabling default actions and transferring text

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() ...

Using jQuery's .append() method within a for loop

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 ...

Tips for resolving the React Hook Type Error issue

Error Image const isLoggedIn = true; const handleChangeEvent = () => {}; const [displayPassword, setDisplayPassword] = useState(false); const handleTogglePassword = () => setDisplayPassword((prevDisplayPassword) => !prevDi ...

Incorporate lively images into a collection

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 ...

Is there a way to include custom headers in the response of socket.io using express.js?

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 ...

Utilizing External Files for Integrating Mixins, Variables, and Functions in Webpack

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 ...

Utilizing Vue.js to display dynamic data within a template using components

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 ...