I need product id that's _id from my mongo document but when I consoled req.params.id it is showing undefined to my /shop page and I'm following mvc format
// get request://
router.get("/shop/:id",userController.shopPage)
//route://
getProductPage: (req, res) => {
try{
let proId = req.params.id;
console.log(proId)
productHelpers
.getProduct(proId)
.then((products) => {
res.render("user/view-product",{products}); })}
catch(error){
}
//get Product//
getProduct: (proId) => {
console.log(proId)
return new Promise((resolve, reject) => {
try {
db.products.find({_id:proId}).then((products) => {
resolve(products);
});
} catch (error) {
console.log(error);
}
});
},
Related
I'm trying to delete some data from a mysql database with the code:
app.delete("/api/deleteHomework/:homeworkName", (req, res) => {
const homeworkName = req.params.homeworkName
connection.query(
"DELETE FROM homework WHERE name = ?",
[homeworkName],
(err, result) => {
if(result){
res.send({ message: result })
console.log(result)
}
if(err){
console.log(err)
}
}
)
})
and then the homeworkName is passed from the front end with the code:
const deleteHw = (homework) => {
Axios.delete(`http://localhost:1337/api/deleteHomework/${homework}`)
.then((response) => {
if(response){
console.log(response)
} else{
console.log("error")
}
})
}
<DeleteForeverIcon className={classes.deleteHwIcon} onClick={() => {deleteHw(value.homeworkName)}} />
However it says the params in the url is undefined:
url: "http://localhost:1337/api/deleteHomework/undefined"
Pass the props "value" directly in the delete function
export default function YourComponent({ value }) {
...
const deleteHw = () => {
Axios.delete(`http://localhost:1337/api/deleteHomework/${value.homeworkName}`) // here
.then((response) => {
if(response){
console.log(response)
} else{
console.log("error")
}
})
}
<DeleteForeverIcon className={classes.deleteHwIcon} onClick={deleteHw} />
Back side
app.delete('/api/deleteHomework/:homeworkName', (req, res) => {
connection.query(`DELETE FROM homework WHERE name=${req.params.homeworkName}`, (err, result) => {
if (err) {
console.log(err);
} else {
res.json(result);
}
});
});
I have some routes
routes.js
var express = require("express");
var router = express.Router();
const { controllerMethod1, controllerMethod2 } = require("./controller");
router.get("/route1", controllerMethod1);
router.get("/route2", controllerMethod2);
module.exports = router;
if i use promise variable as global,
its used by all method in controller.js.
should i use global or local variable for promise ?
controller.js
const {
serviceMethod1,
serviceMethod2,
serviceMethod1ByDate,
} = require("./services");
let promise; //global promise variable
const controllerMethod1 = (req, res) => {
//let promise; local promise variable
//This is for Callback
if (req.query.date) {
serviceMethod1ByDate(req.query.date, (err, result) => {
if (err) {
res.status(500).json({
status: "error",
message: "error using callback",
});
}
if (result) {
res.status(200).json({
status: "success",
message: "success using callback",
});
}
});
} else {
serviceMethod1((err, result) => {
if (err) {
res.status(500).json({
status: "error",
message: "error using callback",
});
}
if (result) {
res.status(200).json({
status: "success",
message: "success using callback",
});
}
});
}
// This is for Promise
promise = req.query.date
? serviceMethod1ByDate(req.query.date)
: serviceMethod1();
Should i use way 1 or way 2 ?
if multiple users request one or more routes at the same time,can handleResponse method work correctly?
Way 1 for promise
promise
.then((results) => {
return res.json({
status: "success with promise variable",
data: results,
});
})
.catch((error) => {
return res.status(500).json({
status: "error with promise variable",
message: "there is no person details",
});
});
Way 2 for Promise
handleResponse(promise, res);
//this method is working for all routes when i use promise
const handleResponse = (results, response) => {
results
.then((result) => {
return response.json({
status: "success with promise variable in handleResponse",
data: result,
});
})
.catch((error) => {
return response.status(500).json({
status: "error with promise variable handleResponse",
message: "Internal Server Error",
});
});
};
controller.js
const controllerMethod2 = (req, res) => {
//------------------ Using Callback Method -------------
serviceMethod2((err, result) => {
if (err) {
res.status(500).json({
status: "error",
message: "error using callback",
});
}
if (result) {
res.status(200).json({
status: "success",
message: "success using callback",
});
}
});
//------------------ Using Promise Method -------------
//local variable
let promise;
promise = serviceMethod2();
//Way 1 for Promise
promise
.then((result) => {
//...
})
.catch((err) => {
//...
});
//Way 2 for Promise
handleResponse(promise, res);
};
module.exports = { controllerMethod1, controllerMethod2 };
service.js
const pool = require("../../../config/database");
//-----------------------Using Callback Mehthod----------------
const serviceMethod1 = async (CallBack) => {
let query = "select * from databse";
await pool.query(query, [], (error, results, fields) => {
if (error) {
return CallBack(error);
}
return CallBack(null, results);
});
};
const serviceMethod1ByDate = async (date) => {
let query = "select * from databse where date ?";
return await new Promise((resolve, reject) => {
pool.query(query, [date], (error, results, fields) => {
if (error) {
return CallBack(error);
}
return CallBack(null, results);
});
});
};
const serviceMethod2 = async (Callback) => {
let query = "select * from database";
await pool.query(query, [], (error, results, fields) => {
if (error) {
return CallBack(error);
}
return CallBack(null, results);
});
};
//-----------------------Using Promise Method----------------
const serviceMethod1 = async () => {
let query = "select * from databse";
return await new Promise((resolve, reject) => {
pool.query(query, [], (error, results, fields) => {
if (results) {
resolve(results);
} else {
reject(error);
}
});
});
};
const serviceMethod1ByDate = async (date) => {
let query = "select * from databse where date ?";
return await new Promise((resolve, reject) => {
pool.query(query, [date], (error, results, fields) => {
if (results) {
resolve(results);
} else {
reject(error);
}
});
});
};
const serviceMethod2 = async () => {
let query = "select * from database";
return await new Promise((resolve, reject) => {
pool.query(query, [], (error, results, fields) => {
if (results) {
resolve(results);
} else {
reject(error);
}
});
});
};
module.exports = {
serviceMethod1,
serviceMethod1ByDate,
serviceMethod2,
};
if i use promise variable as global, its used by all method in controller.js. should i use global or local variable for promise ?
You should use local variable for this type of operation as global variable are generally used to define constants or methods. They cannot be used as temporary values because it's value can be changed anytime and that'll result in conflict with other functionalities and so must be avoided.
Should i use way 1 or way 2 ? if multiple users request one or more routes at the same time,can handleResponse method work correctly?
Way 2 is more efficient that Way 1 because if you use way 1 then you will have to do it for every method in the controller. Way 2 is like a common method where you can format your response and most of the developers use it.
It doesn't make any difference whether you use callbacks or promises but just a clean way to do things.
Instead of using this:
const serviceMethod1 = async () => {
let query = "select * from databse";
return await new Promise((resolve, reject) => {
pool.query(query, [], (error, results, fields) => {
if (results) {
resolve(results);
} else {
reject(error);
}
});
});
};
Use this:
// Remove the async await from here and handle the response/error where the below method is called by putting it in try catch block.
const serviceMethod1 = () => {
let query = "select * from databse";
return new Promise((resolve, reject) => {
pool.query(query, [], (error, results, fields) => {
if (results) {
resolve(results);
} else {
reject(error);
}
});
});
};
// otherFile.js
someMethod = async () => {
try {
const result = await serviceMethod1();
// handle the response
} catch {
// handle the error
}
}
My backend is consist of Api and DB. When I want to get response from DB I have had delayed output by 1 query.
API (I think api is ok. Start read DB first)
app.post('/api/query', (req, res) => {
console.log(`\n Query input : ${JSON.stringify(req.body)}`);
let queryInput = (Object.values(req.body).join(' '));
if(!dbApi.checkArray(queryInput)){ //If array is not made from clear strings
res.json(dbApi.queryFromUser(queryInput));
}
else{
res.json(dbApi.queryOutput);
}
});
app.listen(dbConfig.server.port, () =>
console.log(`Server running on port ${dbConfig.server.port}`));
DB
queryOutput = [];
const receivingQuery =(queryInput) => {
db.query(queryInput, (err, result) =>{
if(err) throw err+' : '+queryInput;
queryOutput = result;
console.log("\nQuery output "+ JSON.stringify(queryOutput)); //Output (result) is ok
});
return queryOutput //Here is Output from previous query (sends to API)
}
module.exports = {
queryOutput: queryOutput,
queryFromUser: receivingQuery,
}
I tryied callback method and I rewrite it couple of times. But I dont have enough skill to solve it.
If You want to return result of query so simply do following things:
add query method to db module:
function query(sql, args = []) {
return new Promise(function(resolve, reject) {
db.query(sql, args, (err, result) => {
if (err) return reject(err);
resolve(result);
});
});
}
// extra feature, getting user by id
async function getUserById(id) {
const result = await query('SELECT * FROM users WHER id = ? LIMIT 1', [id]);
if (Array.isArray(result) && result[0]) return result[0];
return null;
}
module.exports = {
query,
getUserById, // export user by id
queryOutput,
queryFromUser: receivingQuery,
}
use it (with async and await):
app.post('/api/query', async (req, res) => {
try {
console.log('Query input:', req.body);
const queryInput = Object.values(req.body).join(' ');
const result = await dbApi.query(queryInput);
res.json(result);
}
catch (error) {
console.error(error);
res.status(500).json({message: 'Please try again soon'});
}
});
app.get('/api/users/:id', async (req, res) => {
try {
const user = await dbApi.getUserById(req.params.id);
if (!user) return res.status(404).json({message: 'User not found'});
res.status(200).json(user);
}
catch (error) {
console.error(error);
res.status(500).json({message: 'Please try again soon'});
}
});
app.listen(dbConfig.server.port, () =>
console.log('Server running on port', dbConfig.server.port));
How do I use optional query filter on these route like "/employees?department=4" and returning data where department number is 4
app.get("/employees", (req, res) => {
dataService.getAllEmployees().then(function(data) {
res.json(data);
}).catch(function(err) {
var error = { "message": err };
res.json(error);
});
I already have function in dataService module that return a promise of department with id below
function getEmployeesByDepartment(department) {
return new Promise((resolve, reject) => {
try {
employees.forEach((element) => {
if (element.department == department) {
resolve(element);
}
});
} catch (error) {
reject("no data returned");
}
});
}
You can use req.query to fetch query string data and pass department to getEmployeesByDepartment function.
app.get("/employees", (req, res) => {
var department = req.query.department || "";
if(department){
getEmployeesByDepartment(department).then(data => res.json(data));
}
else{
dataService.getAllEmployees().then((data) => {
res.json(data);
}).catch((err) => {
var error = { "message": err };
res.json(error);
}
);
You can access the query parameters using the req.query object.
In your case the code will be something like:
if (req.query.department) {
return getEmployeesByDepartment(req.query.department).then(
data => res.json(data)
);
} else {
return dataService.getAllEmployees().then(
data => res.json(data)
);
}
I'm using React with a Postgres DB with Sequelize.
within my project, I have a promise that is "suppose" to delete all songs relating to the album, using the the Album.id in my state.
** Instead of deleting the rows of songs relating to the Album, after the delete request in the database, it removes the value of the AlbumId of the song. **
Is there an update I am missing
When I console.log outside of the service and in the promise this.state.Album.id remains the same.
It hit's the server with the appropriate number.
This is the function within the React Component
DeleteAlbum (e) {
e.preventDefault()
axios.delete(`${domain}/albums/${this.state.Album.id}`)
.then((res) => {
axios.delete(`${domain}/songs/ByAlbumId/${this.state.Album.id}`)
.then((res) => {
window.location.href = '/#/'
})
.catch((error) => {
console.log('axios error', error)
})
})
.catch((error) => {
console.log('axios error', error)
})
}
This is the Database to the Songs Route
const express = require('express')
const router = express.Router()
const bodyParser = require('body-parser')
const db = require('./../models')
const Song = db.Song
router.use(bodyParser.json({ extended: false }))
const exists = (req) => {
if (typeof parseInt(req.params.id) === 'number') {
Album.findOne({
where: {
id: req.params.id
}
})
.then((album) => {
if (album) {
return true
};
return false
})
.catch((err) => {
return false
})
} else {
return false
}
}
router.delete('/ByAlbumId/:id', function (req, res) {
Song.destroy({
where: {
AlbumId: req.params.id
}
})
.then(function (data) {
return res.json(data)
})
.catch(function (err) {
return res.json({ error: err})
})
})
router.delete('/:id', function (req, res) {
if (exists) {
Song.destroy({
where: {
id: req.params.id
}
})
.then(function (data) {
return res.json(data)
})
.catch(function (err) {
return res.json({ error: err})
})
} else {
res.json({success: false})
}
})
This is the Album Route
const express = require('express')
const router = express.Router()
const bodyParser = require('body-parser')
const db = require('./../models')
const Album = db.Album
router.use(bodyParser.json({ extended: false }))
const exists = (req) => {
if (typeof parseInt(req.params.id) === 'number') {
Album.findOne({
where: {
id: req.params.id
}
})
.then((album) => {
if (album) {
return true
};
return false
})
.catch((err) => {
return false
})
} else {
return false
}
}
router.delete('/:id', function (req, res) {
if (exists) {
Album.destroy({
where: {
id: req.params.id
}
})
.then(function (data) {
return res.json(data)
})
.catch(function (err) {
return res.json({ error: err})
})
} else {
res.json({success: false})
}
})
If I place console logs all over the place, the output is what I expect it to be. There's is just something going wrong with Deleting two songs from my app. I can delete multiple songs if I hit the server directly with postman
Any idea?
You are actually destroying the album, before you destroy the songs.
In this case, since they probably have onDelete: 'SET NULL' option added, you will just de-associate the songs with that album.
Your fix will be to just replace the order of your calls :
// First we delete the songs and then the album
axios.delete(`${domain}/songs/ByAlbumId/${this.state.Album.id}`)
.then((res) => {
axios.delete(`${domain}/albums/${this.state.Album.id}`)
.then((res) => {