Home > Net >  Simple delete request with Postman not working
Simple delete request with Postman not working

Time:10-17

Have a simple phonebook app created with node.js, express, mongo db and mongoose.

Get and Post requests are working fine, Post requests are stored on the Mongo database.

Delete requests on postman are not working however, get a 404 not found status on postman.

I think I'm not referencing the id of the entry I want to delete properly.

When I copy one of my entries from my database these are the details.

{"_id":{"$oid":"6169f8bc950d87ffe2f6f033"},"name":"nick","number":"087-26387784","__v":{"$numberInt":"0"}}

Also tried using findOneAndDelete({_id: req.params.id}) but that didn't work either.

Any help appreciated

const express = require('express');

const router = express.Router();

const Entry = require('../models/entry');



router.get('/api/entries', (req, res, next) => {

    Entry.find({}).then(entries => {

      res.json(entries)

      console.log(entries)

    })

  }) 

// add now entry to db

router.post('/api/entries', function(req, res, next){

    Entry.create(req.body).then(function(entry){

        res.send(entry);

    }).catch(next);

});



router.delete('api/entries/:id', function(req, res, next){

    Entry.findByIdAndRemove({_id: req.params.id}).then(function(entry){}).res.send(entry);

    });

module.exports = router;




const express = require('express');
const mongoose = require('mongoose');

const password = process.argv[2]

const routes = require('./routes/api');

const app = express();
mongoose.connect(`mongodb srv://nick:${password}@cluster0.tvs6a.mongodb.net/phoneBook?retryWrites=true&w=majority`)
.then(result => {
  console.log('connected to MongoDB')
})
.catch((error) => {
  console.log('error connecting to MongoDB:', error.message)
})
//mongoose.Promise = global.Promise;

const cors = require('cors');

app.use(express.json());
app.use(routes);
app.use(function(err, req, res, next){
  //console.log(err);
  res.status(422).send({error: err.message});

});



const PORT = 3001
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`)
})




const mongoose = require('mongoose');

// Entry Schema
const EntrySchema = new mongoose.Schema({
    name: {
       type: String,
       required: [true, 'Name field is required']
    },
    number: {
      type: String,
      required: [true, 'Number field is required']
    }  
  })

  EntrySchema.set('toJSON', {
    transform: (Entry, returnedObject) => {
      returnedObject.id = returnedObject._id.toString()
      delete returnedObject._id
      delete returnedObject.__v
    }
  })

// Entry model
const Entry = mongoose.model('entry', EntrySchema);

module.exports = Entry;

CodePudding user response:

you're missing the / at the beginning of the path:

router.delete('/api/entries/:id', function(req, res, next) {
    /// Here --^
    Entry.findByIdAndRemove({_id: req.params.id}).then(function(entry){}).res.send(entry);
});
  • Related