简体   繁体   中英

Trouble Deleting Object in Mongo Collection (Express / Monk)

I am trying and failing to delete an object from a mongo collection that I created. I can make get and post requests just fine, but I am totally lost as to how to delete an item from a given collection. I am currently just deleting the entire collection when trying to pass in the item by id...

Just so you can see what I am working with...

/**** IMPORTS *****/
const express = require('express');
const cors = require('cors');
const monk = require('monk');

const app = express();

const db = monk('localhost/att');
// Mongo Collection packs holds package objects
const packs = db.get('packages');

app.use(cors());
app.use(express.json());

And my back-end delete path:

//packs is my collection
app.delete('/packages/:id', (req, res) => {
    packs.remove({"_id": req.body.id});
});

and my function on the front-end:

function listAllPackages() {
    fetch(API_URL_PACKAGES).then(response => response.json()).then(packageObjs => {
        // Access to all the package objects in DB here
        // packageObjs : Array of Packages
        let html = '';
        packageObjs.forEach(p => {
            html += `<option id="${p._id}" name="${p._id}">${p._id} - Name: ${p.name}, Price: ($)${p.price}, Duration: ${p.duration}(minutes)</option>`;
        });
        allPackages.innerHTML = html;
        const delPackageDiv = document.querySelector('.deletePackage');
        delPackageDiv.innerHTML = `<button id='deletePackageSubmit'>DELETE PACKAGE</button>`;
        const delPackageButton = document.querySelector('#deletePackageSubmit');
        delPackageButton.addEventListener('click', () => {
            // GET SELECTED PACKAGE
            const delForm = document.querySelector('.showPackages');
            const opt = delForm.options[delForm.selectedIndex];
            fetch(API_URL_PACKAGES + '/' + opt.id, {
                method: 'DELETE'
            });
        });
    });
}

Figured it out finally. Here's my solution in case anyone else is struggling like I was...

Change this:

//packs is my collection
app.delete('/packages/:id', (req, res) => {
    packs.remove({"_id": req.body.id});
});

To this:

//packs is my collection
app.delete('/packages/:id', (req, res) => {
    packs.remove({"_id": req.params.id });
});

Voila!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM