Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 140817

Mongodb - Express, how to get the "id" properly? It gives an empty [Object, Object]

$
0
0

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));

Viewing all articles
Browse latest Browse all 140817

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>