REST API Express - DELETE Endpoint

I'm facing an issue with the delete functionality in my API. In order to use my application, a user must log in and then they can add courses. These courses are stored in a nested array within the User model. I want users to be able to remove (delete) a course from the interface and have it deleted from their profile on the server as well. Despite having identical variables, I keep receiving a 404 response.

Below is the ajax call I am using to delete a specific course:

jQuery.ajax({
    url: "/test/signups/5387c1a0fb06e48f4658170c", 
    type: "DELETE",

    success: function (data, textStatus, jqXHR) { 
      console.log("Response:"); 
      console.dir(data); 
      console.log(textStatus); 
      console.dir(jqXHR); 
    }
  });

This is the delete method implementation:

app.delete('/test/signups/:id', isLoggedIn, function(req, res) {
    User.findOne({'_id': req.user.id }, function(err, user) {
        if (err)
           return done(err);

    if (user) {
        var found = false;
        var singlesignup = user.signup.filter(function(e){ return e._id == req.params.id })[0]

        user.signup.forEach(function (singlesignup, index) {
            if (singlesignup._id === req.params.id) {
                found = index;
            }
        });

        if(found) {
            user.signup.splice(found, 1);
            res.json(200, {status: 'deleted'});
        } else {
            res.json(404, {status: 'survey question deletion invalid'});
        }
    }       
   });
});

Answer №1

In MongoDB, the _id values are not stored as strings but rather as instances of the ObjectId class. This can cause issues when using the == or === operators for comparison. To address this, it is recommended to convert the _id to a string before performing any comparisons, like so:

singlesignup._id.toString() === req.params.id
. For optimal accuracy in your code, be sure to account for all scenarios including null, string, or ObjectId. Utilizing a helper library such as objectid can simplify this process.

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 express route parser is incorrectly detecting routes that it should not

I am encountering an issue with the following two routes: router.get('/:postId([0-9]*)', handler) router.get('/:postId([0-9]*)/like', handler) The first route is intended to only capture URLs like /posts/4352/, not /posts/3422/like. ...

Ways to split up array objects in an axios GET request

Hello, I recently implemented an AXIOS GET request that returns an array of objects. However, the current example I am using retrieves the entire array at once, and I need to separate the objects so that I can work with them individually. class CryptoAP ...

A monotonous4 express always fails to provide a response

I'm utilizing express4-tedious to construct a SQL web API Below is the code I am using: const express = require('express'); // OAuth2 requires a web server for callback const morgan = require('morgan'); // HTTP middlewar ...

"Encountered an issue while trying to access the 'forEach' property of an undefined entity in Express

I encountered an issue when trying to post on an API built with Express.js and SQL Server DB. Fortunately, I discovered a solution that worked for me: const express = require('express'); const bodyParser = require('body-parser'); const ...

Switching the language setting in Node.js for internationalization purposes

I need help changing the locale in i18n. https://github.com/mashpie/i18n-node This is how I have configured it: i18n.configure({ // setup some locales - other locales default to en silently locales:['en', 'de'], // where ...

Important: Express 4 and Passport Issue with Session Creation

So far, I have managed to successfully log users in using Facebook. However, once I retrieve the information from Facebook, it seems to get lost. I'm not sure if I should be responsible for creating the session or if there is something crucial that I ...

In React production, the use of .map as a function is unavailable

While my express react app build runs smoothly locally with the map function, the transition to production triggers an error stating that 'map' is not a function. The error specifically points to the line declaring 'let returnlist'. Be ...

What are the steps to store my information in MongoDB with the help of Expressjs?

As a backend developer beginner, I am currently working with an array called Movie using expressJS. My goal is to save this array in a MongoDB database, specifically using Mongodb Atlas. Any help or guidance on this process would be greatly appreciated. I ...

Interactive PayPal quick checkout feature

Currently, I am in the process of developing an online store for a personal project and this piece of code is extracted from my application. <div class="row"> <script src="https://www.paypalobjects.com/api/checkout.js"></script> {{#e ...

What is the process for setting up extra routes in an Express server that is configured to work with React-Router

Currently, my server is set up to return index.html for every app.use(/* API call that is made. When I try to create a new route using app.get('/info', it still returns the index.html file. I am looking for a way to add new routes without having ...

What is the most efficient way to toggle boolean values in a JSON object using Express?

After completing my first MERN CRUD app as a beginner, which is a todo list with a complete button that scores out items, I am looking for ways to enhance it. Currently, when the complete button is clicked, a post request is sent to the nodejs/express ba ...

Is there a way to change the format of the date "Wed Jan 01 2020 00:00:00 GMT+0530 (India Standard Time)" to JAN 01, 2020 in JavaScript?

I am currently retrieving the date from the database in the format of Wed Jan 01 2020 00:00:00 GMT+0530 (India Standard Time), but I would like it to be displayed in the JAN O1,2020 format without using moment.js. Is there any alternative approach to ach ...

What causes the default value to fail in a mongoose schema when no input is given?

This is my specific Schema and I'm having trouble with the image default value when the HTML input field is left empty before submitting a "blog" post. let blogSchema = new mongoose.Schema({ title: String, image: { type: String, ...

Incapable of retrieving data from MongoDB due to a failure in fetching results using streams in Highland.js

I have recently started working with streams and I am experimenting with fetching data from my collection using reactive-superglue/highland.js (https://github.com/santillaner/reactive-superglue). var sg = require("reactive-superglue") var query = sg.mong ...

Uploading Files to the Server with Angular 2 and ExpressJS

In my Angular-2 project, I am currently working on uploading files to the server. The code snippet provided below showcases how the file is uploaded: My main question pertains to linking these uploaded files to specific mongodb documents. How can I achiev ...

The REST API request returns a response code of 0

I have been attempting to make an API call to the Insightly API using this code: var x = new XMLHttpRequest(); x.open("GET", "https://api.insight.ly/v2.2/Projects/Search?status=in%20progress&brief=false&count_total=false", true); x.setRequestHeade ...

What steps can you take to intentionally cause errors in a Node Express application in order to capture them in Sentry?

Currently, I am utilizing log4js logger with node express to log errors to a file. However, the log files are quite difficult to interpret and I rarely look at them. I recently integrated Sentry into my project. I want to be able to manually send errors t ...

Options for Localhost Cookies

I'm currently working on a Chrome Extension that customizes the Google Calendar UI based on configurations stored on my server. Everything is running smoothly in production. However, I'm encountering issues when trying to test it in development. ...

The console is reporting that the term "next" has not been

I am currently working on a project and I am trying to validate my jwt token using a middleware. However, I encountered an error message in the console stating "next is not defined". Here is the code snippet: In login.js const verifyToken = require(&apos ...

Can you share tips for passing a variable from a post request to a function that accepts parameters as a string or an array of strings in Node.js?

I am struggling to insert the variable named query into the end of the prompt. I attempted to use template literals but it was unsuccessful. (async () => { const gbtResponse = await openai.createCompletion({ model: "text-davinci-002", prompt ...