Sharing user_id value between two MySql table - javascript

I'm working on my middleware AuthController.js below. The middleware is part of a CRUD app. I created exports.create which when requested will collect the first name and last name from the CRUD form. Once collected the MySql INSERT query, will insert the data on the MySql user table which is working fine.
What I cannot achieve and I need help is that together with the first name and last name info I want to insert also the variable { user_id: decoded.id }, decoded.id is a variable which take the user_id value from another MySql table called login.
When I request export.create the following error shows on the terminal:
(node:18780) UnhandledPromiseRejectionWarning: TypeError: argument callback must be a function when provided
Basically I want that the value under user_id column from the login table is transferred to the user_id column on user table. Thank for any help.
exports.create = async (req, res, next) => {
if (req.cookies.jwt) {
try {
//1)verify the token
var decoded = await promisify(jwt.verify)(req.cookies.jwt,
process.env.JWT_SECRET
);
// console.log(decoded);
const { first_name, last_name } = req.body;
connection.query('INSERT INTO user SET first_name = ?,last_name = ?', { user_id: decoded.id }, [first_name, last_name,], (err, rows) => {
if (!err) {
res.render('add-crew', { alert: 'Crew member added succesfully!' });
} else {
console.log(err);
}
console.log('The data from user table:\n', rows);
});
} catch (error) {
console.log(error);
return next();
}
}
};

The connection.query function takes in two to three arguments: the SQL statement, (the values) and the callback. Here, the function is taking four arguments, so it thinks [first_name, last_name,] is the callback.
What you can do is:
...
connection.query('INSERT INTO user SET user_id = ?, first_name = ?,last_name = ?', [decoded.id, first_name, last_name,], (err, rows) => {
if (!err) {
res.render('add-crew', { alert: 'Crew member added succesfully!' });
} else {
console.log(err);
}
console.log('The data from user table:\n', rows);
});
...
I hope this is what you are looking for.
Edit you could also do:
...
connection.query('INSERT INTO user SET ?', {user_id: decoded.id, first_name: first_name, last_name: last_name}, (err, rows) => {
if (!err) {
res.render('add-crew', { alert: 'Crew member added succesfully!' });
} else {
console.log(err);
}
console.log('The data from user table:\n', rows);
});
...

Related

How to return ID when new entry is recorded with a trigger express js and MYSQL

I am currently using express and workbench to configure a database where I can create, view and update cars.
Right now when I POST a new car it creates a new entry with the inputs manufacturer, model and price, and I use a trigger which I used inside workbench to configure a UUID for each vehicle. However, I want to be able to return this new UUID when a new record is created in my app.post function.
Here is my post function:
//Allow post methods
app.post('/cars', (req, res) => {
if (req.query.manufacturer && req.query.model && req.query.price) {
console.log('Request received'); //logging to check if post request has beeen made
connection.connect(function(err) { //query the connection then call an SQL INSERT method to put new record in database.
connection.query(`INSERT INTO main.cars (manufacturer, model, price) VALUES ('${req.query.manufacturer}', '${req.query.model}', '${req.query.price}')`, function(err, result, fields) {
if (err) res.send(err);
if (result) res.send({manufacturer: req.query.manufacturer, model: req.query.model, price: req.query.price}); //sending the fields to the response (res)
if (fields) console.log(fields);
console.log(result)
});
});
} else {
console.log('Missing a parameter');
}
});
Right now it just returns the new fields inputted in postman but not the new uuid (id) and am quite unsure how to do this, as it is created in a trigger in workbench:
CREATE DEFINER=`admin`#`%` TRIGGER `cars_BEFORE_INSERT`
BEFORE INSERT ON `cars` FOR EACH ROW BEGIN
SET new.id = uuid();
END
Query the table to get the id that was assigned to the manufacturer/model that was just inserted.
Also, use a database query with parameters rather than substituting request parameters directly into the SQL, to protect against SQL injection.
connection.connect(function(err) { //query the connection then call an SQL INSERT method to put new record in database.
connection.query('INSERT INTO main.cars (manufacturer, model, price) VALUES (?, ?, ?)', [req.query.manufacturer, req.query.model, req.query.price], function(err, result, fields) {
if (err) {
res.send(err);
} else {
connection.query('SELECT id FROM main.cars WHERE manufacturer = ? AND model = ?', [req.query.manufacturer, req.query.model], function(err, result) {
if (err) {
res.send(err);
} else {
res.send({
manufacturer: req.query.manufacturer,
model: req.query.model,
price: req.query.price,
id: result[0].id
});
}
});
}
});
});

Mongoose - How to Chain Save So Data Can Be Saved to Multiple Collections

I have read all sorts of variations of this on stackoverflow but I cannot seem to find a post that exactly explains what I'm trying to achieve, at the same time I believe this has to be a very common task during saving data.
So I need to save data to one collection and then read the _id from that doc and save it to a doc in a different collection. I have the following code and I can see the correct data with console.log but I don't see the data being saved to the database.
Appreciate if someone can guide me in the right direction.
Thank you!
router.post('/signup', async (req, res) => {
const { email, password, name, country } = req.body;
try {
const user = new User({ email, password });
await user.save((error, doc) => {
if (error) {
console.log(error);
} else {
const userProfile = new UserProfile({ userId: doc._id, name, country });
userProfile.save((error, doc) => {
if (error) {
console.log(error)
} else {
console.log(doc) // Can see this log with the correct data
}
});
}
});
const token = jwt.sign({userId: user._id}, 'MY_KEY');
res.send({ token });
} catch(error) {
return res.status(422).send(error.message)
}
})

How to get data with just inserted data with Sequelize in PostgreSql?

I want to get updated table values after I add user to my "WOD" table. For instance, I have 2 users in my WOD table and after I add third user , I want to return a response to client with I have just inserted data (third guy). But now , I can only return first 2 users because I can not take updated values. Of course I can make another query to get updated table values after I insert, but is there any better solution ? Here is my codes;
const addUser = async (req, res) => {
try {
const { userId, wodId } = req.body;
if (!userId || !wodId) {
res.status(400).send({ status: false, message: 'need userId and wodId' });
}
const wod = await Wod.findByPk(wodId, {
include: [
{
model: User,
as: 'Participants',
through: { attributes: [] }
}
]
});
//check capacity if full.
if (wod.Participants.length >= wod.capacity) {
res
.status(403)
.send({ status: false, message: 'Capacity of this class is full!' });
}
const result = await wod.addParticipants(userId);
res.status(201).json({ status: !!result, wod });
} catch (error) {
res.status(500).send({ status: result, message: error.message });
console.log(error.message);
}
};
As a result of many-to-many association sequelize.sync will generate some functions for us. You are used addParticipants function and this returns an array that added to the assocation(userwod) table.
In this array you will find some id fields(join table fields) because you just run like this INSERT INTO 'user_wods' ('user_id''wod_id') VALUES (2,1). If you want to return the added user's information then you should run a SELECT * FROM 'user' WHERE 'id'=2.
You must call reload function for fetch the third guy.
await wod.reload()

Variable value updation gives value change to null

I have an application that is connected to this route. This route is to update the user personal detail, I don't get any errors in the process but for some reason what ever I put the input, the value on the mongodb is changed to null.
app.post('/updateUserDetails', verifyToken, function(req, res){
jwt.verify(req.token, 'secretkey', (err, authData) => {
if(err) {
res.sendStatus(403);
} else {
var userID = authData._id,
newFirstName = req.firstName;
// lastName = req.lastName,
// age = req.age,
// gender = req.gender,
// phoneNumber = req.body.phoneNumber;
console.log(err);
user.update({_id: userID}, {firstName: newFirstName}, function(err, updatedUser){
if(err){
console.log("error updating user firstName");
res.json({msg:"error updating user firstName"});
}else{
console.log("user firstName has been updated");
res.json({msg:"user firstName has been updated", firstName: newFirstName});
}
},function(err){
console.error(err);
});
}
});
});
Console.log your req see exactly what you are sending, you can also use the debugger to understand what is being sent and received at any point.
console req.firstname and check what will print. try req.body.firstName, your route is post call

How to create an update function on nodejs/mongodb?

Hi I am currently new to nodejs and mongodb what I want to do is make a function to update my win,lose,draw record from my userschema.
My Schema:
UserSchema = new mongoose.Schema({
username:'string',
password:'string',
email:'string',
//Change Made
win:{ type: Number, default: 0 },
lose:{ type: Number, default: 0 },
draw:{ type: Number, default: 0 }
});
My Function for updating:
//Update scores
app.post("/user/updateScores", function (req, res) {
var user = new User({
username:req.body.username,
win:req.body.win,
lose:req.body.lose,
draw:req.body.draw
});
Users.findOne({ username : req.params.username }, function(error, user) {
if (error || !user) {
res.send({ error: error });
} else {
user.update(function (err, user) {
if (err) res.json(err)
req.session.loggedIn = true;
res.redirect('/user/' + user.username);
});
}
});
});
The problem is when I try updating, when I try updating via my html file. It does not update anything and just stays the same (the values win,lose,draw the default value is 0 so when I logout and login again the values of the win,lose,draw record is still zero). I thoroughly checked if the problem was the html and javascript functions that I have made but this is not the case so I think that the problem is the update function I have made. Any of you guys have an idea where I went wrong? Thanks!
Assuming your post is being called correctly from the client, you'll need to be careful about variable and parameter names, as the scope right now is that you're saving an exact duplicate of the user object that was just fetched via findOne.
You had user declared as a variable of the post callback, and then again within the findOne. The inner variable user will take precedence.
app.post("/user/updateScores", function (req, res) {
var username = req.body.username;
Users.findOne({ username : username }, function(error, user) {
if (error || !user) {
res.send({ error: error });
} else {
// update the user object found using findOne
user.win = req.body.win;
user.lose = req.body.lose;
user.draw = req.body.draw;
// now update it in MongoDB
user.update(function (err, user) {
if (err) res.json(err) {
req.session.loggedIn = true;
}
res.redirect('/user/' + user.username);
});
}
});
});

Categories

Resources