req.params returns undefiened - node.js

I'm trying to get back the ID from the params but it keeps sending back undefiened, what would be the problem here and how can i solve it ?
this is the route:
app.delete(`${api_version}/delete-branch/:id`, verifyToken, branches.deleteBranch)
this is the controller:
exports.deleteBranch = (req, result) => {
const {branch_id} = req.params
console.log(branch_id) // => returns undefined
if(branch_id === undefined) {
result.status(404).send({
message: 'This branch does not exist',
statusCode: 404
})
} else {
// console.log(req.params)
Branches.deleteBranch(branch_id, (err, data) => {
if (err) {
result.status(500).send({
message: err.message
})
} else {
result.status(200).send({
message: 'Branch deleted successfully',
statusCode: 200,
data
})
}
})
}
}

You need to destruct req.params like this:
const {id} = req.params
instead of:
const {branch_id} = req.params
Or either defined the route as follow:
app.delete(`${api_version}/delete-branch/:branch_id`, verifyToken, branches.deleteBranch)
and then destruct const {branch_id} = req.params;

Related

res.status is not a function - express

I have a route to get user details. Here is the controller :
module.exports.getUser = (req, res) => {
if (req.method == "GET") {
const userDetails = `SELECT * FROM users WHERE id = ${req.params.id}`;
sql.query(userDetails, function (err, res) {
if (res.length > 0) {
res.status(200).json({ res })
} else {
res.status(401).json({ message: "Error with this id !" })
}
})
}
}
When i make a request to the url, I have this error :
TypeError: res.status is not a function
at Query.<anonymous> (/Applications/MAMP/htdocs/my-app/controllers/auth.controller.js:9:21)
Line 9 is res.status(200).json({ res })
Is there an error in this method ?
Thank you
If I understand your issue correctly, as per your comments. You have to change the variable you are using in sql query callback not the one you are receiving in getUser function
module.exports.getUser = (req, res) => {
if (req.method == "GET") {
const userDetails = `SELECT * FROM users WHERE id = ${req.params.id}`;
sql.query(userDetails, function (err, user) {
if (user.length > 0) {
res.status(200).json({ user })
} else {
res.status(401).json({ message: "Error with this id !" })
}
})
}
}
Something like this should work.

Why mongo query is showing undefined in node js

I'm trying to check the data with findOne when im trying with the postman getting undefined in console.log , i checked with the same query in roboMongo and its showing the data
this is the result:-
Here is the code:-
exports.signIn = async( req, res ) => {
const {
userEmailPhone,
} = req.body;
await User.findOne ({ email : userEmailPhone}).then((err, user)=> {
console.log("user..", user)
if (user){
res.status(200).send({
message: "sucess"
});
}
})
}
the postman response:-
Since you are already using async - await, I believe there is no need of using the .then() block.
Your code should be updated to use async and await as below:
exports.signIn = async( req, res ) => {
const { email } = req.body;
const user = await User.findOne ({ email : userEmailPhone})
console.log("user..", user)
if (user){
res.status(200).send({
message: "sucess"
});
}
}
If you still want to use the .then() block, I would recommend making the following changes in the code:
exports.signIn = async ( req, res ) => {
const {email} = req.body;
User.findOne ({ email : email}).then((user, err)=> {
console.log("user..", user)
if (user){
res.status(200).send({
message: "sucess"
});
}
})
}
Since the promise callback for MongoDb queries has the following callback format:
.then( (res, err) => {
// do stuff
})
Reference : https://docs.mongodb.com/drivers/node/fundamentals/promises/
You are sending raw json data. First you should use app.use(bodyParser.json());. Only app.use(bodyParser()); is deprecated.
This should fix it assuming you have a json body-parser
exports.signIn = async( req, res ) => {
const {email} = req.body;
User.findOne ({ email : email}).then((err, user)=> {
console.log("user..", user)
if (user){
res.status(200).send({
message: "sucess"
});
}
})
}

Cast to ObjectId failed for value ... at path "_id" for model but I am not doing any query

I have an express route that gets call with axios from the frontend. The thing is, not matter what I put into the route I always get the same error:
"Cast to ObjectId failed for value "getTodosMisProductos" at path "_id" for model "local""
I'm not doing any query to mongoose in that route but in any other route where I make a query everything works fine.
I've checked the middleware but there is not any query to mongoose
getTodosMisProductos
router.get("/getTodosMisProductos", auth, async (req, res) => {
/*
try {
const data = await Local.findOne({ user: req.user.id }).populate("products.producto");
console.log(data);
if (!data) {
return res
.status(404)
.json({ errors: [{ msg: "No se encontro el local" }] });
}
return res.status(200).json(data.products);
} catch (error) {
console.log(req.user.id);
console.error("error en llamado");
return res.status(500).send("Server Error");
}
*/
console.log("algo");
return res.status(200).json({ msg: "success" });
});
the code commented is the code I need to use, I changed it for testing purposes but even with that simple new code I get the same error.
auth middleware
const jwt = require("jsonwebtoken");
const config = require("config");
module.exports = function (req, res, next) {
// Get token from header
const token = req.header("x-auth-token");
// Check if not token
if (!token) {
return res
.status(401)
.json({ msg: "No tienes autorización para hacer esto" });
}
// Verify token
try {
const decoded = jwt.verify(token, require("../config/keys").jwtSecret);
req.user = decoded.user;
next();
} catch (error) {
res.status(401).json({ msg: "El token es inválido" });
}
};
action from where the route gets called
export const getAllProductos = () => async (dispatch) => {
try {
console.log("Esto se llama");
const res = await axios.get("/api/local/getTodosMisProductos/");
dispatch({
type: SET_PRODUCTS,
payload: res.data,
});
} catch (err) {
const errors = err.response.data.errors;
if (errors) {
errors.forEach((error) => dispatch(setAlert(error.msg, "danger")));
}
}
};
The response status is always 500 (Internal Server Error)
EDIT
//#route GET api/local/:id
//#desc obtener local por id
//#access private
router.get("/:id", auth, async (req, res) => {
try {
const local = await Local.findById(req.params.id);
if (!local) {
return res
.status(404)
.json({ errors: [{ msg: "No se encontro el local" }] });
}
return res.status(200).json(local);
} catch (error) {
console.error(error.message);
res.status(500).send("Server Error");
}
});
You have another route that also match /api/local/getTodosMisProductos/
Apparently it got matched with /api/local/:id,
where you get req.params.id = "getTodosMisProductos" and got passed down to await Local.findById(req.params.id)
And mongoose can't convert "getTodosMisProductos" to ObjectId, hence the error.
The order in which you declare the route affects the matching priority.
The order is first comes first serves, so make sure you declare /api/local/addProducto or any other routes that starts with /api/local/ before declaring /api/local/:id

Node.js route sends to the incorrect controller

Problem: When I call this route /topproducts it enters in the orders_get_order function and not in the orders_most_ordered_products. This is very strange I can't understand why it enters in the wrong function.
The console error message:
message: 'Cast to ObjectId failed for value "topproducts" at path "_id" for model "Order"',
name: 'CastError',
stringValue: '"topproducts"',
kind: 'ObjectId',
value: 'topproducts',
path: '_id',
reason: undefined,
model: Model { Order }
My route.js
router.get("/topproducts", checkAuth, OrdersController.orders_most_ordered_products);
My controller order.js
exports.orders_most_ordered_products = async (req, res) => {
try{
let order = await order_service.get_most_ordered_products();
if ('error' in order){
res.status(order['status']).json(order)
}else{
res.status(200).json(order)
}
}catch(err){
console.log("most orders")
console.log(err)
//res.status(500).json(fatal_error_status);
}
};
//get uma order
exports.orders_get_order = async (req, res) => {
try{
let order = await order_service.get(req.params.orderId);
if ('error' in order){
res.status(order['status']).json(order)
}else{
res.status(200).json(order)
}
}catch(err){
console.log("get orders")
console.log(err)
//res.status(500).json(fatal_error_status);
}
};
And then it sends to the service order.js
exports.orders_most_ordered_products = async (req, res) => {
try{
let order = await order_service.get_most_ordered_products();
if ('error' in order){
res.status(order['status']).json(order)
}else{
res.status(200).json(order)
}
}catch(err){
console.log("most orders")
console.log(err)
}
};
exports.orders_get_order = async (req, res) => {
try{
let order = await order_service.get(req.params.orderId);
if ('error' in order){
res.status(order['status']).json(order)
}else{
res.status(200).json(order)
}
}catch(err){
console.log("get orders")
console.log(err)
}
};
The problem was the order of the routes, the route that takes an Id as a parameter was first so the server though I was calling that one.
router.get("/topproducts", checkAuth, OrdersController.orders_most_ordered_products);
router.get("/:orderId", checkAuth, OrdersController.orders_get_order);

Unable to pull record from array

I am trying to remove an item from an array of objects by using Mongoose 'pull'. I am getting a status code of 200 and apparently everything is fine but the record is not actually removed? The userId in mongo db looks like:
userId: ObjectId("6b275260a6g58308e510721b")
exports.putDislike = (req, res, next) => {
const productId = req.body.productId;
const userId = req.body.userId;
Product.findById(productId)
.then(product => {
if (!product) {
return next(new Error('Product not found.'));
}
product.requests.pull(userId)
return product.save()
.then(result => {
res.status(200).json({ message: "Item request removed." });
})
})
.catch(err => {
res.status(500).json({ message: "Removing request failed." });
});
};
I'm not sure you are using pull correctly, check out this link https://docs.mongodb.com/manual/reference/operator/update/pull/
According to that, i think your code should be somehing like the example below:
exports.putDislike = (req, res, next) => {
const productId = req.body.productId;
const userId = req.body.userId;
Product.update(
{ "_id": productId },
{ $pull: { requests: {userId: userId} } })
.then(result => {
res.status(200).json({ message: "Item request removed." });
})
.catch(err => {
res.status(500).json({ message: "Removing request failed." });
});
};

Resources