Removing a value from an array contained within an object

I have a scenario in my task management application where I want to remove completed tasks from the MongoDB database when a logged-in user marks them as done. Below is the snippet of code for my Schema.

const user = new mongoose.Schema({
    username : String,
    password : String,
    task : [{
        text : String,
        day : String,
        reminder : Boolean,
    ]}
 })
    

As an example, let's say Daryl completes the task with text : "Gym" & day : "Feb 4th 5.30pm". In such cases, I only want to delete the specific task entry from Daryl's task array.

Below is my attempt to achieve this using Mongoose,

app.delete("/tasks", (req,res) => {
    User.findOne( {_id : req.user.id}).then((target) => {
        target.task.remove({text : req.body.text, day : req.body.day})
        })
}) 
  1. Use User.findOne({_id : req.user.id}) to target the logged-in user
  2. Access the task array by using .task once targeted
  3. Utilize .remove along with filters to eliminate the specific task from the array

Even after logging all the variables, which match with the data fields, the task entry is not being removed. Can anyone help me identify what mistake I may be making here?

Answer №1

After numerous attempts, I was finally able to resolve my issue. Hopefully, my solution can be beneficial to someone else who may encounter the same problem.

app.post("/delete-tasks", (req, res) => {
    User.findByIdAndUpdate(req.user.id, {$pull: {"task": {text: req.body.text}}}, {safe: true, upsert: true},
        function (err, result) {
        // Add console.log statements for debugging purposes
        })
})

This method effectively removes items based on the following criteria:

  1. User's ID
  2. "task" : {//insert your specific conditions here}

Despite previous failed attempts, I am pleased that this approach proves successful.

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

Create a form with two submission buttons along with a captcha verification system

I'm currently developing a booking page form that requires a unique functionality. I need a single form where clients can enter their information, followed by two submit buttons at the bottom. The first button should hold their reservation for 72 hour ...

What steps can I take to position tsParticles behind all other elements in my NextJS project?

In full disclosure, I am not a web developer, so my setup may be incorrect. Currently, the particles are covering all other elements on the page. I would like them to be positioned behind the rest of the elements and only show as a background. import Imag ...

Configuring a Meteor.js application requires defining variable scopes for templates in order to manage

Is there a way to define a variable that is limited in scope to a specific template? I want this variable to be accessible by multiple helpers within the template, but not outside of it. For example, how can the game variable be shared between two templat ...

Exploring the concepts of express post and delete responses that are unclear

It appears that I am facing an issue where trying to access an attribute of an element from a JSON file returns null. Additionally, I am still encountering npm audit problems. What are your thoughts on this situation? Below is the code snippet that has be ...

What is the best way to close all other accordion tabs when selecting one?

A simple HTML code was created with the full pen accessible here. <div class="center"> <div class="menu"> <div class="item"> <button class="accordionBtn"><i class=&q ...

Guide on setting up Tailwind CSS and material-tailwind concurrently within the tailwind.config.js configuration file

I am looking to integrate both Tailwind and Material Tailwind in a Next.js 14 project. Below is my customized tailwind.config.ts file (already configured with Tailwind CSS): import type { Config } from 'tailwindcss' const config: Config = { ...

React.js - state variable becomes undefined upon uploading app to Amplify

I am encountering a perplexing error and am struggling to determine the root cause. To provide a brief overview, I have a dialog containing a jsonschema form along with an image that is uploaded to an input and saved in b64 format within a state variable c ...

Disable the outer div scrolling in VueJS, but re-enable it once the inner div has reached the bottom of

I am currently working on a webpage that contains multiple divs stacked vertically. Here is the concept I am working with: Once the scrollbar reaches the bottom of the first div, the outer scrollbar will be disabled and the inner scrollbar will be enabled ...

What could be causing the ERROR TypeError in an Angular form where "_co.service.formData" is undefined?

My attempt to create a form in Angular 7 has resulted in an error message: ERROR TypeError: "_co.service.formData is undefined" Here is the HTML code for the component: <form (sumbit)="signUp(form)" autocomplete="off" #form="ngForm"> <div clas ...

getStaticProps function in Next.js fails to execute

My [slug].js file includes two Next.js helper functions, getStaticPaths and getStaticProps. These functions are exported and create the path posts/[slug]. I have also added a post file named hello.json. However, when I try to access localhost:3000/posts/he ...

Experimenting with the input type generated by the Form Helper tool

Before generating the form using Form Helper, is there a method to preview the type of input it will produce? I would like to confirm whether it will result in a select or multi-select element before loading the page. ...

Unable to modify div style using a JS function

I am attempting to show different divs based on the button clicked, with all starting with a display style of "none" except for one default div called "atualizacoes". After clicking a button, all divs should be set to display="none", and then the specific ...

"Using jQuery to prevent propagation from interfering with an ajax GET request

I'm facing an issue with a table that has clickable rows and ajax links in the rightmost column. Whenever I click on the link within a row, the row's click event is triggered as well. To prevent the event propagation, I tried using stopPropagati ...

Display options in Material-UI autocomplete only upon clicking the icon

Is there a way to display the options list only when clicking on the arrow icon as opposed to the textfield itself? I have reviewed the documentations without success in finding a solution. Example ...

The use of 'process.argv' and 'process.argv.slice(1)' does not seem to be functioning properly within Cypress

Currently, I am utilizing Cypress with JavaScript for my automation testing needs. My current task involves storing the user-passed command to run a script. Allow me to elaborate: Below is an excerpt from my package.json file: "scripts": { &q ...

Ways to retrieve data from an AJAX success callback function

Within my front end JavaScript application, I need to execute an ajax request in order to retrieve data from the server. Once this data is acquired, I aim to display it within the view. var retrievedData; $.ajax({ url:"/getDataFromServer.json", ty ...

Tips on managing ASP .NET API's HttpResponseMessage for file downloads

I came across a solution on how to download a file from an asp.net API at this link: As a result, I created an API handler with the following code: public HttpResponseMessage Post([FromBody]dynamic result) { var localFilePath = graph ...

Using JQuery to Refresh a Div and Trigger an API Call with a Click Event

Currently, I am working on developing a web application that generates random quotes dynamically. Using JQuery, I can successfully make an API call and retrieve JSON data to display a quote. To allow users to fetch new quotes with the click of a button, I ...

Concealed Content Within Drawer Navigation

When using the Material UI permanent drawer component in different pages, I encountered an issue where the main content was getting hidden behind the drawer's toolbar and sidebar. I am unsure how to fix this problem. It seems like a styling issue, bu ...

What is the best way to combine two bytes in Java?

I have a variable named writePos which holds an integer value between 0 and 1023. My goal is to store this integer in the last two bytes of a byte array called bucket. To achieve this, I need to express it as a combination of the array's final two byt ...