Getting an Error: slugify: string argument expected - javascript

I try to create category to eCommerce project then it throws an error
Postman - throws an error
These are source codes
location: ecommerce-backend\index.js
const express = require('express')
const env = require('dotenv')
const app = express()
const mongoose = require('mongoose')
//routes
const authRoutes = require('./routes/auth')
const adminRoutes = require('./routes/admin/auth')
const categoryRoutes = require('./routes/category')
const productRoutes = require('./routes/product')
const cartRoutes = require('./routes/cart')
//environment variable or you can say constants
env.config()
//mongodb connection
mongoose.connect(
`mongodb+srv://${process.env.MONGO_DB_USERS}:${process.env.MONGO_DB_PASSWORD}#cluster0.nglbc.mongodb.net/${process.env.MONGO_DB_DATABASE}?retryWrites=true&w=majority`,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
}
).then(() => {
console.log('Database connected')
});
app.use(express.json())
app.use('/api', authRoutes)
app.use('/api', adminRoutes)
app.use('/api', categoryRoutes)
app.use('/api', cartRoutes)
app.use('/api', productRoutes)
app.listen(process.env.PORT, () => {
console.log(`Server is running on port ${process.env.PORT}`)
})
location: ecommerce-backend\routes\category.js
const express = require('express')
const { requireSignin, adminMiddleware } = require('../common-middleware')
const { addCategory,getCategories } = require('../controller/category')
const router = express.Router()
const path = require('path')
const shortid = require('shortid')
const multer = require('multer')
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(path.dirname(__dirname), 'uploads'))
},
filename: function (req, file, cb) {
cb(null, shortid.generate() + '-' + file.originalname)
}
})
const upload = multer({ storage })
router.post('/category/create',requireSignin, adminMiddleware,upload.single('categoryImage'), addCategory)
router.get('/category/getcategory', getCategories)
module.exports = router
location: ecommerce-backend\models\category.js
const mongoose = require('mongoose')
const categorySchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
slug: {
type: String,
required: true,
unique: true
},
categoryImage: {
type: String,
},
parentId: {
type: String
}
}, { timestamps: true})
module.exports = mongoose.model('Category',categorySchema)
location: ecommerce-backend\controller\category.js
const Category = require('../models/category')
const slugify = require('slugify')
function createCategories(categories, parentId = null){
const categoryList = []
let category
if(parentId == null){
category = categories.filter(cat => cat.parentId == undefined)
}else{
category = categories.filter(cat => cat.parentId == parentId)
}
for(let cate of category){
categoryList.push({
_id: cate._id,
name: cate.name,
slug: cate.slug,
children: createCategories(categories,cate._id)
})
}
return categoryList
}
exports.addCategory = (req, res) => {
const categoryObj = {
name: req.body.name,
slug: slugify(req.body.name)
}
if(req.file){
categoryObj.categoryImage = process.env.API + '/public/'+ req.file.filename
}
if(req.body.parentId){
categoryObj.parentId = req.body.parentId
}
const cat = new Category(categoryObj)
cat.save((error,category) => {
if(error) return res.status(400).json({ error})
if(category){
return res.status(201).json({ category})
}
})
}
exports.getCategories = (req,res) => {
Category.find({})
.exec((error, categories) => {
if(error) return res.status(400).json({error})
if(categories){
const categoryList = createCategories(categories)
res.status(200).json({categoryList})
}
})
}
this is my .env file at ecommerce-backend\ .env
PORT = 2000
MONGO_DB_USERS = mrzombit
MONGO_DB_PASSWORD = ********
MONGO_DB_DATABASE = ecommerce
JWT_SECRET = MERNSECRET
API = http://localhost:2000
I face this problem then I can't figure it out what happened to my code
Thank you!

Make sure you have change the 'Content-Type' in postman header section.
Content-Type: multipart/form-data; boundary=<calculated when request is sent>

I just do below steps:
Delete slugify package from package.json
Reinstall slugify package : you will see that
found 2 high severity vulnerabilities
run npm audit fix to fix them, or npm audit for details
Run npm audit fix
Open new window ! in postman and
copy the token from /api/admin/create and paste this token in the new window: /api/category/create in body ,
form-data :
name (doesn't exist in your DB yet)
categoryImage (click file not text)

You can also try with the following code which I hope would work for you.
**slug: slugify(toString(req.body.name))**

Add
slug: { type: String, slug: "title"} to your model.

I tried to debug the problem of slugify: string argument expected & found that in my case this object is comeing as {} so it was throwing slugify: string argument expected.
try to find if all values are properly received in slugify method.
Code snippet
Schema.pre('save', (next)=> {
console.log(`pre hook is triggered ${this.name}`.silly);
// this.set({ updatedAt: new Date() });
this.slug = slugify(this.name,{lower:true})
next()
})

Related

GraphQL Subscription Configuration Error

Good day, I am trying to make a simple app where , when user add any product subscriber will trigger and event and send back the product.I've implemented some code with help of google everything is working excepts subscriber, When I browse graphiql in my browser I see some error like Expected { query: { kind: "Document", definitions: [Array], loc: [Object] }, mutation: { Query: [Object], Mutation: [Object], Subscription: [Object], Upload: Upload } } to be a GraphQL schema.
, Here is my code below ,
Server main index.js file
const express = require('express')
const morgan = require('morgan')
const cors = require('cors')
const bodyParser = require('body-parser')
const {ApolloServer, gql} = require('apollo-server-express');
const {createServer} = require('http');
const {execute, subscribe} = require('graphql');
const {makeExecutableSchema} = require('#graphql-tools/schema');
const {PubSub} = require('graphql-subscriptions');
const {SubscriptionServer} = require('subscriptions-transport-ws');
const typeDefs = require("./GraphQLSchema/typeDef")
const resolvers = require("./GraphQLSchema/resolvers")
const myGraphQLSchema = require('./GraphQLSchema');
const coreRouting = require("./routes")
require('dotenv').config()
const app = express()
app.use(bodyParser.json())
//app middleware
app.use(morgan('dev'));
//app.use(cors())
const {PrismaClient} = require("#prisma/client")
const prisma = new PrismaClient();
async function checkPrismaConnection() {
const obj = {
include: {transactions: true}
}
try {
// const result = await prisma.product.findMany({
// include: {transactions: false}
// });
const result = await prisma.transaction.findMany();
console.log(result);
} catch (e) {
console.log(e);
}
}
//checkPrismaConnection();
app.use(coreRouting);
app.get('/test/route', (req, res) => res.send('Hello World!'))
const serverPort = process.env.PORT || 9000
app.use('/graphql', bodyParser.json());
const apolloServer = new ApolloServer(
{
typeDefs,
resolvers,
context: ({req}) => ({req, pubsub})
});
apolloServer.applyMiddleware({app});
const pubsub = new PubSub();
const server = createServer(app);
//const schema = makeExecutableSchema({typeDefs, resolvers});
server.listen(serverPort, () => {
new SubscriptionServer({
execute,
subscribe,
pubsub,
schema: {
query: typeDefs,
mutation: resolvers,
},
graphiql: true
}, {
server: server,
path: '/graphql',
});
});
typeDefs Code
const {gql} = require("apollo-server-express");
module.exports = gql`
type Post{
body: String!
}
type Product{
id: Int!
name: String!
transactions:[Transaction]!
}
type Transaction{
id: Int!
quantity: Int!
time: String!
}
input ProductInput{
name: String!
}
type Query {
getPosts: [Post]
products: [Product]
product(id: ID!): Product
}
type Mutation {
createProduct(productInput: ProductInput):Product!
}
type Subscription {
newProduct: Product!
}
`
Resolvers Code
const {helperMethodForFetcingProducts, helperMethodForCreateProduct} = require("../../helper");
const {relationalKeyword} = require("../../helper/keyword");
module.exports = {
Query: {
getPosts() {
return [{"body": "First Post"}, {"body": "2nd Post"}, {"body": "3rd Post"}]
},
products: async function () {
return helperMethodForFetcingProducts(relationalKeyword, false);
},
product: async function (_, {id}) {
console.log(_, id);
return helperMethodForFetcingProducts(relationalKeyword, true, parseInt(id));
}
},
Mutation: {
createProduct: async (_, {productInput: {name}}, {pubsub}) => {
let getProductFromMethod = await helperMethodForCreateProduct(name);
pubsub.publish('Proudct_Added', {
newProduct: getProductFromMethod
})
return getProductFromMethod;
}
},
Subscription: {
newProduct: {
subscribe: (_, __, {pubsub}) => pubsub.asyncIterator('Proudct_Added')
}
}
}
My Error
Since I am new in graphQL I don't understand the issue actually.

NodeJS MonogoDB Postman Post Request throwing an Error probably the objectID Error

hi there I am learning node js quite a while but facing an error which becomes to really hard to fix it for my own self after spending to much time I got the cause of which is I may be passing ObjectID in a wrong manner although my endpoint is working ok I can't call post-call in POSTMAN. here are some snippets
POSTMAN Post request by Json
{
"genreId":"5f65c490db297fa17cd4f060",
"title": "Trminator",
"numberInStock": 0,
"dailyRentalRate": 0
}
ERROR in terminal
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'genreId' of undefined
at C:\Users\Sharjeel MK\Desktop\Project- Build the Genres API\routes\movies.js:16:47
index.js
const express = require ('express');
const app=express();
const home=require('./routes/home');
const genres=require('./routes/genres');
const customers=require('./routes/customers');
const movies = require('./routes/movies')
const mongoose=require('mongoose');
mongoose.connect('mongodb://localhost/vidly',{
keepAlive: true,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
})
.then(()=>console.log("connected")).
catch((e)=>console.log('not connnected',e));
app.use('/',home);
app.use('/vidly.com/api/genres',genres);
app.use('/vidly.com/api/customers',customers);
app.use('/vidly.com/api/movies',movies);
const port=process.env.PORT||3000;
app.listen(port,()=>{
console.log(`${port} listening`);})
in routes movie.js
const {Movie, validate} = require('../model/movieModel');
const {Genre} = require('../model/genreModel');
const mongoose = require('mongoose');
const express = require('express');
const routes = express.Router();
routes.get('/', async (req, res) => {
const movies = await Movie.find().sort('name');
res.send(movies);
});
routes.post('/', async (req, res) => {
const { error } = validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
const genre = await Genre.findById(req.body.genreId);
if (!genre) return res.status(400).send('Invalid genre.');
let movie = new Movie({
title: req.body.title,
genre: {
_id: genre._id,
name: genre.name
},
numberInStock: req.body.numberInStock,
dailyRentalRate: req.body.dailyRentalRate
});
movie = await movie.save();
res.send(movie);
});
routes.put('/:id', async (req, res) => {
const { error } = validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
const genre = await Genre.findById(req.body.genreId);
if (!genre) return res.status(400).send('Invalid genre.');
const movie = await Movie.findByIdAndUpdate(req.params.id,
{
title: req.body.title,
genre: {
_id: genre._id,
name: genre.name
},
numberInStock: req.body.numberInStock,
dailyRentalRate: req.body.dailyRentalRate
}, { new: true });
if (!movie) return res.status(404).send('The movie with the given ID was not found.');
res.send(movie);
});
routes.delete('/:id', async (req, res) => {
const movie = await Movie.findByIdAndRemove(req.params.id);
if (!movie) return res.status(404).send('The movie with the given ID was not found.');
res.send(movie);
});
routes.get('/:id', async (req, res) => {
const movie = await Movie.findById(req.params.id);
if (!movie) return res.status(404).send('The movie with the given ID was not found.');
res.send(movie);
});
module.exports = routes;
schema model of movies
const Joi = require('joi');
const mongoose = require('mongoose');
const {genreSchema} = require('./genreModel');
const Movie = mongoose.model('Movies', new mongoose.Schema({
title: {
type: String,
required: true,
trim: true,
minlength: 5,
maxlength: 255
},
genre: {
type: genreSchema,
required: true
},
numberInStock: {
type: Number,
required: true,
min: 0,
max: 255
},
dailyRentalRate: {
type: Number,
required: true,
min: 0,
max: 255
}
}));
function validateMovie(movie) {
const schema = {
title: Joi.string().min(5).max(50).required(),
genreId: Joi.string().required(),
numberInStock: Joi.number().min(0).required(),
dailyRentalRate: Joi.number().min(0).required()
};
return Joi.validate(movie, schema);
}
exports.Movie = Movie;
exports.validate = validateMovie;
User findOne -> here is the syntax
var query = {
genreId : req.body.genreId
}
Model-Name.findOne(query, function(err, result){
if(err) throw err
else res.send(200, result)
})
so after spending 2 days finally figure out the error the reason was so much simpler I didn't pass express.json() in my index.js file for incoming Request Object as a JSON Object. that's why it was throwing the error cause not handle properly.
Previous code
const express = require ('express');
const app=express();
const home=require('./routes/home');
const genres=require('./routes/genres');
const customers=require('./routes/customers');
const movies = require('./routes/movies')
const mongoose=require('mongoose');
mongoose.connect('mongodb://localhost/vidly',{
keepAlive: true,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
})
.then(()=>console.log("connected")).
catch((e)=>console.log('not connnected',e));
app.use('/',home);
app.use('/vidly.com/api/genres',genres);
app.use('/vidly.com/api/customers',customers);
app.use('/vidly.com/api/movies',movies);
const port=process.env.PORT||3000;
app.listen(port,()=>{
console.log(`${port} listening`);})
updated code
const express = require ('express');
const app=express();
const home=require('./routes/home');
const genres=require('./routes/genres');
const customers=require('./routes/customers');
const movies = require('./routes/movies')
const mongoose=require('mongoose');
mongoose.connect('mongodb://localhost/vidly',{
keepAlive: true,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
})
.then(()=>console.log("connected")).
catch((e)=>console.log('not connnected',e));
app.use(express.json());
app.use('/',home);
app.use('/vidly.com/api/genres',genres);
app.use('/vidly.com/api/customers',customers);
app.use('/vidly.com/api/movies',movies);
const port=process.env.PORT||3000;
app.listen(port,()=>{
console.log(`${port} listening`);
})

How to dynamically pass API data to MongoDB database

I am building a boat visualizer using AISHub APIs. After inquiring the APIs I am able to obtain a json file with the vessels and filter with only the vessel I am interested in, and inject them into a table on the webpage. The API gives the following fileds:
[NAME, MMSI, LONGITUDE, LATITUDE]. I can correctly connect to MongoDB as I npm start.
The problem: I would like to send also this data to a collection in to MongoDB database every 5 minutes. I tried many different way to do that, but none of them seems to be working.
It was very difficult to think which parts of the code to pass and which not, but below I believe there are enough information to understand what the problem is:
app.js is where I set the MongoDB connection
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var mongoose = require('mongoose');
const bodyParser = require('body-parser');
const vesselController = require('./controllers/VesselController');
require('./config/keys');
var app = express();
app.use(cors());
app.options('*', cors());
// DB Config
const db = require('./config/keys').MongoURI;
const options = {
useNewUrlParser: true,
reconnectTries: Number.MAX_VALUE,
poolSize: 10
};
mongoose
.connect(db, options)
.then(() => console.log('MongoDB Connection established'))
.catch((err) => console.log('Error connecting MongoDB database due to: ', err));
const PORT = process.env.PORT || 3000;
app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));
app.use(bodyParser.json({ limit: '50mb' }));
app.use(cors());
app.route('/vessels/all').get(vesselController.getBaseAll);
app.route('vessels/:id/track').get(vesselController.getCurrent);
app.route('/vessels').get(vesselController.getHistory);
app.listen(PORT, console.log(`Server started on port ${PORT}`));
module.exports = app;
index.js is where I am caching the data (and where I think the app should send data to MongoDB)
var express = require('express');
var router = express.Router();
var axios = require('axios');
const NodeCache = require('node-cache');
const myCache = new NodeCache();
let hitCount = 0;
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
const mmsiOfInterest = [
'367029520',
'366909730',
'367128570'
];
const shipNamesOfInterest = [
'MICHIGAN',
'JP BOISSEAU',
'DELAWARE BAY'
];
router.get('/hello', async function(req, res, next) {
const allData = myCache.get('allData');
if (!allData) {
hitCount++;
console.log(`hit ${hitCount} number of times`);
const { data } = await axios.get(
'http://data.aishub.net/ws.php?username=KEY&format=1&output=json&compress=0&latmin=11.42&latmax=58.20&lonmin=-134.09&lonmax=-52.62'
);
const [ metaData, ships ] = data;
console.log(data);
const shipsOfInterest = ships.filter(
(ship) => mmsiOfInterest.includes(ship.MMSI) || shipNamesOfInterest.includes(ship.NAME)
);
myCache.set('allData', shipsOfInterest, 70);
res.send(data);
return;
}
res.send(allData);
});
module.exports = router;
VesselController.js: is where I have the functions for getting different information such as currect vessel, all vessels, history of vessels
module.exports.getBaseAll = (req, res) => {
Promise.all([
Compnanies.find(),
Vessels.find(),
Positions.aggregate([
{
$sort: {
date: -1
}
},
{
$group: {
_id: '$callsign',
details: {
$push: '$$ROOT'
}
}
},
{
$replaceRoot: {
newRoot: {
$arrayElemAt: [ '$details', 0 ]
}
}
}
])
])
.then(([ companies, vessels, positions ]) => {
// apply vessels detail table as join:
positions.forEach((pos) => {
vessels.forEach((ves) => {
if (pos.callsign == ves.callsign) {
p._detail = ves;
}
});
companies.forEach((com) => {
if (p._detail.company == com.number) {
p._detail = com;
}
});
});
res.status(200).json(positions);
})
.catch((err) => {
return res.status(500).send(err);
});
console.log(vesselController.getBaseAll);
};
module.exports.getHistory = (req, res) => {
var id = req.param.id;
Positions.find(
{
callsign: id,
date: {
$gte: new Date(Date.now() - 1000 * 60 * 60 * 24)
}
},
(err, task) => {
if (err) {
return res.status(500).send(err);
}
res.status(200).json(task);
}
);
console.log(vesselController.getHistory);
};
module.exports.getCurrent = (req, res) => {
var currentPos = Positions.find({
date: {
$gte: new Date(Date.now() - 1000 * 60 * 60)
}
});
currentPos.exec((err, task) => {
if (err) {
return res.status(500).send(err);
}
res.status(200).json(task);
});
console.log(vesselController.getCurrent);
};
In LatitudeLongitude.js I set the proper format according to MongoDB documentation
const mongoose = require('mongoose');
const LatitudeLongitudeSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
mmsi: {
type: Number,
required: false
},
longitude: {
type: Number,
required: false
},
latitude: {
type: Number,
required: false
}
});
const LatitudeLongitude = mongoose.model('LatitudeLongitude', LatitudeLongitudeSchema);
module.exports = LatitudeLongitude;
users.js is where I set the router.post
var express = require('express');
var router = express.Router();
const LatitudeLongitude = require('../models/LatitudeLongitude');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.post('/vessles/map', function(req, res) {
const { name, mmsi, longitude, latitude } = req.body;
let errors = [];
// Check required fields
if (!name || !mmsi || !longitude || !latitude) {
errors.push({ msg: 'No data received' });
}
if (
LatitudeLongitude.findOne({ mmsi: mmsi }).then((pos) => {
if (pos) {
// vessel exists
const newVessel = new Vessles({
name,
mmsi,
longitude,
latitude
});
}
})
);
});
module.exports = router;
Below the collection set inside MongoDB, which is clearly empty:
How can I successfully pass information from the API I mentioned above, into my MongoDB?
What I have donbe so far:
I tried many different ways to pass data from the API to MongoDB every 5 minutes. Among the dirfferent approaches, the one I included in this post are, I think, the most effective, however there is something missing I can't catch/understand.
I believe that the file index.js should be the one that is in charge of taking care of doing that, as I pre-set all the check in that file. However I am now confused whether that is the right location or not.
the reasons why you see the routes as app.route('/vessels/all').get(vesselController.getBaseAll); in the app.js file is because I will use that as end point api check with Postman once everything is working. I figured I would leave it there so you see how I designed the process.
Thanks for shedding light on this matter.
In my opinion, you should first test my approach by attaching following code to your server.js file. then refactor it
setInterval( () => {
fetch('http://your/get/route').
then( updateDB() ).
catch(doWhateverYouWant());
},3000
);

Sequelize.js/Node.js/Express.js: Tasks.findAll()returns a TypeError:Cannot read property 'findAll' of undefined

code is supposed to return a a JSON object with empty tasks when requesting /tasks instead it returns a message error- TypeError: cannot read property 'findAll' of undefined. The source of errors as per the message comes from routes >tasks.js see below for screenshots or/and live code on sandbox.
Project Folder:
sandbox
some codes:
src>models >tasks.js
module.exports = (sequelize, DataType) => {
const Tasks = sequelize.define(
"Tasks",
{
id: {
type: DataType.INTEGER,
primaryKey: true,
autoIncrement: true
},
title: {
type: DataType.STRING,
allowNull: false,
validate: {
notEmpty: true
}
},
done: {
type: DataType.BOOLEAN,
allowNull: false,
defaultValue: false
}
},
{
classMethods: {
associate: models => {
Tasks.belongsTo(models.Users);
}
}
}
);
return Tasks;
};
src>routes>tasks.js
module.exports = app => {
const Tasks = app.db.models.tasks;
app.get("/tasks", (req, res) => {
Tasks.findAll({}).then(tasks => {//source of error as per error message
res.json({ tasks: tasks });
});
});
};
src >db.js
var path = require("path");
var fs = require("fs");
var Sequelize = require("sequelize");
//const config = require("./libs/config.js");
var sequelize = null;
let db = null;
module.exports = app => {
if (!db) {
const config = app.libs.config;
sequelize = new Sequelize(
config.database,
config.username,
config.password,
config.params
);
db = {
sequelize,
Sequelize,
models: {}
};
const dir = path.join(__dirname, "models");
fs.readdirSync(dir).forEach(file => {
const modelDir = path.join(dir, file);
const model = sequelize.import(modelDir);
db.models[model.name] = model;
});
Object.keys(db.models).forEach(key => {
db.models[key].options.classMethods.associate(db.models);
});
}
return db;
};
src>index.js
var express = require("express");
var consign = require("consign");
var app = express();
consign({ cwd: "src" })
.include("./libs/config.js")
.then("db.js")
.then("./libs")
.then("./routes")
.into(app);
On file routes/tasks.js line 2, add a capital on task;
const Tasks = app.db.models.Tasks;
Then it should works.

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

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));
You are not providing the valid mongoose object id.
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!

Categories

Resources