I want to save the id of a ticket from feedback page into DB, how can I do this?
The problem is in this line "const ticketId = 'ticketId';",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
js code:
const ticketId = 'ticketId';
let rating =[];
$(".starrr").each((index)=>{
rating.push({
_id:$(`.star-c-${index}`).attr("id"),
value:parseInt($(`.star-c-${index}`).attr("data-rating"))
})
});
const comment = $("#comment-feedback").val();
const feedbackObj = {
comment:comment,
rating:rating
}
controller:
const feedbackform = async (req, res) => {
Rating.find({delete: false, school : req.session.currentSchool._id}).exec(function(err, ratings){
if(err)
{
console.log(err)
}
else
{
console.log(ratings);
req.flash('success', 'Successfully saved feedback');
res.render("ticket_feedback",{ratingDetail:ratings, ticketId:req.params.id})
}
})
};
router.get('/feedbackform/:id', feedbackform);
link:
Feedback
Related
Building a shopping cart where I can duplicate the row of details of a product from shop database to cart database in Mysql where each user has their own cart.
I had successfully appended the product into the cart database already but the row of the details isn't duplicated into the cart database.
const express = require('express');
const router = express.Router();
const moment = require('moment');
const Product = require('../models/Product');
const ensureAuthenticated = require('../helpers/auth');
const flashMessage = require('../helpers/messenger');
require('dotenv').config();
const fetch = require('node-fetch');
// Required for file upload
const fs = require('fs');
const upload = require('../helpers/imageUpload');
const AddToCart = require('../models/Cart');
Here is the product inventory, add, edit and remove
router.get('/listProduct', ensureAuthenticated, (req, res) => {
let userRole = req.user.userrole;
if (userRole == "s")
Product.findAll({
order: [['brand', 'DESC']],
raw: true
})
.then((product) => {
res.render('product/listProduct', { product });
})
.catch(err => console.log(err));
});
router.get('/addProduct', ensureAuthenticated, (req, res) => {
let userRole = req.user.userrole;
if (userRole == "s")
res.render('product/addProduct');
});
router.post('/addProduct', ensureAuthenticated, (req, res) => {
let brand = req.body.brand;
let product = req.body.product;
let description = req.body.description;
let posterURL = req.body.posterURL;
let size = req.body.size.toString();
let color = req.body.color;
let price = req.body.price;
let userId = req.user.id;
console.log(userId)
Product.create(
{ brand, product, description, posterURL, size, color, price, userId }
)
.then((product) => {
console.log(product.toJSON());
res.redirect('/product/listProduct');
})
.catch(err => console.log(err))
});
This is the shop part, and so far so good over here
router.get('/shop', ensureAuthenticated, (req, res) => {
Product.findAll({
order: [['brand', 'DESC']],
raw: true
})
.then((product) => {
res.render('product/shop', { product });
})
.catch(err => console.log(err));
});
and this is the part where the cart didn't work well, and also, every users are sharing the same cart at the moment.
router.get('/cart', ensureAuthenticated, (req, res) => {
AddToCart.findAll({
order: [['brand', 'DESC']],
raw: true
})
.then((product) => {
res.render('product/cart', { product });
})
.catch(err => console.log(err));
});
router.get("/addToCart/:id", async (req, res) => {
let id = req.params.id;
let userid = req.user.id;
var prod = await Product.findOne({
where: {
id: id
}
});
AddToCart.create(prod);
return res.redirect("/product/cart");
});
index.js file
var users = [];
let addUser = (userId, socketId) => {
!users.some((user) => user.userId === userId) &&
users.push({ userId, socketId });
};
let removeUser = (socketId) => {
users = users.filter((item) => item.socketId !== socketId);
};
const getUser = (userId) => {
console.log("inside function", users);
return users.find((item) => item.userId === userId);
};
io.on("connection", (socket) => {
socket.on("addUser", async (userId) => {
await addUser(userId, socket.id);
io.emit("getUsers", users);
console.log(users) // print array of users like this
// [{userId:'userId',socketId: 'socket id'}]
});
socket.on("disconnect", () => {
removeUser(socket.id);
io.emit("getUsers", users);
});
});
const socketIoObject = io;
const usersInObject = users;
module.exports.ioObject = { socketIoObject, usersInObject };
controller file
exports.createNotifications = async (req, res) => {
try {
const { userId, title, type = "default", isPublic } = req.body;
if (!title) {
return res.status(401).send("Data is required");
}
const notification = await notificationsModel.create({
userId,
title,
type,
isPublic: userId ? false : true,
});
console.log("socket", socket.ioObject.usersInObject); // return empty
// array [] !!!!
return res.status(200).send("sent");
} catch (err) {
return res.status(400).send(err.message);
}
};
why I can't get the users list in the controller, I got an empty array !!
I need to share the users list in all files to can get the user by function getUser to get the socketId of a specific user to can send a notification to him
Maybe, you import socket in controller file incorrect
i have a table:
CREATE TABLE IF NOT EXISTS bands (
id serial PRIMARY KEY,
name VARCHAR UNIQUE NOT NULL,
creationDate DATE not NULL,
years DATE not NULL
);
I only want to pass name and creation date. what i want is that years will return currentdate - creationDate. The problem is that I do not really know where i should correctly change my code, because im using Node project.
My code looks like this:
const express = require("express");
const app = express();
const pool = require("./db");
app.use(express.json());
// Routes
app.post("/bands", async (req, res) => {
try {
const { name, creationDate } = req.body;
const newBand = await pool.query(
"INSERT INTO bands (name, creationDate,years) VALUES ($1, $2) RETURNING *",
[name, creationDate]
);
res.json(newBand);
} catch (err) {
console.error(err.message);
}
});
app.get("/bands", async (req, res) => {
try {
const allBands = await pool.query("SELECT * FROM bands");
res.json(allBands);
console.log(allBands);
} catch (err) {
console.error(err.message);
}
});
app.get("/bands/:bandsName", async (req, res) => {
console.log(req.params);
const { bandsName } = req.params;
try {
const todo = await pool.query("SELECT * FROM bands WHERE name = $1", [
bandsName,
]);
res.json(todo.rows[0]);
} catch (err) {
console.error(err.message);
}
});
app.put("/bands/:id", async (req, res) => {
try {
const { id } = req.params;
const { name, creationDate } = req.body;
const updateTodo = await pool.query(
"UPDATE band SET name = $1, creationDate = $2 WHERE id = $3",
[name, creationDate, id]
);
res.json("Udało się, zaaktualizowane");
} catch (err) {
console.error(err.message);
}
});
app.delete("/bands/:id", async (req, res) => {
try {
const { id } = req.params;
const deleteTodo = await pool.query("DELETE FROM bands WHERE id = $1", [
id,
]);
res.json("Usunięto");
} catch (err) {
console.error(err.message);
}
});
app.listen(3000, () => {
console.log("server is listening on port 3000");
});
Can anyone tell me where should i change my code so "years" will automatically calculate without me having to put the data in postman?
const { name, creationDate } = req.body;
const d = new Date(creationDate );
const year = d.getFullYear();
Create a date object and retrieve the year would do it
I am working on a node js application and using DB as mysql what I am trying to do is when I run a query and all data is fetched I want to access the data or store that data to variables for further use
In my controller I am writing this code
exports.login = function(req, res) {
User.fetchUser()
.then(([rows]) => {
console.log(rows)
})
.catch(err => console.log(err));
}
this one is printing on console like [ BinaryRow { email: 'draj.8126#gmail.com', password: 'dheeraj' } ]
in my model class I am executing my fetchUser function
static fetchUser() {
const email = 'draj.8126#gmail.com'
const password = 'dheeraj'
let sql = 'SELECT email,password FROM tpconsumer where email = ? and password = ?'
return db.execute(sql, [email, password]);
}
Now what I am trying to do is get email and password values and store them in variable for further use, or simply how can I use email or my password I want to access them
Try to pass params to your fetchUser method
exports.login = function(req, res) {
User.fetchUser(email,password)
.then(([rows]) => {
if(rows.length >0)
{
for(var i=0; i<rows.length; i++){
console.log(rows[i].email);
console.log(rows[i].password);
}
}
else{
console.log('Nothing to fetch');
}
})
.catch(err => console.log(err));
And in your Class Model :
static fetchUser(email,password) {
/*const email = 'draj.8126#gmail.com'
const password = 'dheeraj'*/
//pass your data dynamically
let sql = 'SELECT email,password FROM tpconsumer where email = ? and password = ?'
return db.execute(sql, [email, password]);
}
The result we get after executing query will be an array. so please try this
user.fetchUser().then(rows => {
console.log(rows);
var email = rows[0].email;
var passw = rows[0].pass;
console.log("email--",email);
console.log("passw--",passw);
}).catch(err => {
console.log(err)
})
How I want my data to be structured is as follows:
Student -> Reg_num -> someindex (that will start from 1 - like an
unique key) -> course details.
However, the code I wrote gives me an incorrect structure. Can someone help me sort it out.
var db = admin.database();
var ref = db.ref("Students");
var newMessageRef = ref.push();
exports.uploadFile = functions.https.onRequest((req, res) => {
cors(req, res, () => {
var uniqueID = 97888888888888;
if (req.method !== 'POST') {
return res.status(500).json({
message: 'Not allowed'
})
} else {
return newMessageRef.set({
[uniqueID]: {
course: req.body.course,
credits: req.body.credit,
lecturer : 'Prof. Lee'
}
}).then(() => {
res.status(200).json({
message: "okkkkasss"
});
...
Note: The -LC-lS2HPMbZW9AdT19K is a code that was automatically added from the code. This is because I used ref.push()
Do not use ref.push() or ref.set(), but ref.update() as follows:
const db = admin.database();
const ref = db.ref("Students");
//var newMessageRef = ref.push(); <- Don't do that
exports.uploadFile = functions.https.onRequest((req, res) => {
cors(req, res, () => {
const uniqueID = 97888888888888; <- Student ID
const uniqueCourseKey = 0; <- uniqueCourseKey
if (req.method !== 'POST') {
return res.status(500).json({
message: 'Not allowed'
})
} else {
return ref.child(uniqueID).update({
[uniqueCourseKey]: {
course: req.body.course,
credits: req.body.credit,
lecturer : 'Prof. Lee'
}
}).then(() => {
res.status(200).json({
message: "okkkkasss"
});
....
Then you can call again the Cloud Function with e.g. const uniqueCourseKey = 1; and the new node will be correctly added under the StudentID node.
The doc for the update method is here: https://firebase.google.com/docs/reference/js/firebase.database.Reference#update