Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (19.9k points)

I am trying to build an application with MERN stack, here is my Item model:

const Item = require("../../models/Item");

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

//Create Schema

const ItemSchema = new Schema({

  name: {

    type: String,

    required: true

  },

  createdAt: {

    type: Date,

    default: Date.now

  },

  handler:{

    type:String,

    required:true

  }

});

module.exports = Item = mongoose.model("item", ItemSchema);

delete function with the mongoose objectId:

router.delete("/:id", auth, (req, res) => {

  var id =  mongoose.Schema.Types.ObjectId(req.params.id);

  Item.deleteOne({ _id: id})

    .then(() => {

      console.log(id);

      res.json({ success: true });

    })

    .catch(err => {

      console.log(err);

      res.status(404).json({ success: false });

    });

});

The result of the console.log(id) is:

undefined

I've tried different versions, for example with the Mongodb ObjectId

const ObjectID = require("mongodb").ObjectId;

router.delete("/:id", auth, (req, res) => {

  var id = ObjectID(req.params.id).toString();

  Item.deleteOne({ _id: id})

    .then(() => {

      console.log(id);

this console.log(id) gives:

Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

I console.log(req.params) and the result:

params: { id: '[object Object]' }

How can I retrieve id properly to delete the item from Mongodb database ? My action file in React is like that:

export const deleteItem = itemId => dispatch => {

  dispatch({ type: LOADING_ITEMS });

  axios

    .delete(`http://localhost:5000/api/items/${itemId}`)

    .then(res => {

      console.log(itemId)

      dispatch({

        type: DELETE_ITEM,

        payload: itemId

      });

    })

    .catch(err => console.log(err));

1 Answer

0 votes
by (25.1k points)

mongoose object id you are providing is invalid.

const express = require("express");

const mongoose = require("mongoose");

const app = express();

const port = 3000;

app.delete("/:id", (req, res) => {

  if (!mongoose.Types.ObjectId.isValid(req.params.id)) {

    return res.send("Please provide valid id");

  }

  var id = mongoose.Types.ObjectId(req.params.id);

  console.log(id);

  return res.send("Hello World!");

});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

Here are the curl requests:

curl -X DELETE http://localhost:3000/1 # Please provide valid id 

curl -X DELETE http://localhost:3000/4edd40c86762e0fb12000003 # Hello World!

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...