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