I've been working on a project that involves sequelize(MySQL DB).
So I have a table "InterestRate" that takes id's from two other tables(foreign keys).
bankId is stored in "Banks" table and interId is stored in another table called "Interest".
Now I want to populate this table with Postman by sending this data:
{
"bank": "BankName",
"inter": "Interest",
"nks": "4.11",
"eks": "6.24",
"time": "36"
}
BUT I want to populate table with the primary keys of these values(if existed in their own table). E.g When I send to postman I want to check table "Banks" and search "BankName" grab its id in that table, and put it in new table. Same thing for this inter thing.
Code that I have rn is trash, I know why it doesn't work but I'm really stuck.
(req, res) => {
const bank = req.body.bank;
const type = req.body.type;
const nks = req.body.nks;
const eks = req.body.eks;
const time = req.body.time;
InterestRate.create({
bankId: bank,
interId: type,
NKS: nks,
EKS: eks,
time: time,
})
.then(() => {
res.status(200).json({ message: 'Added successfully' });
})
.catch((err) => {
res.status(500).send('Error -> ' + err);
});
};
Note that all models etc. are set up correctly, it works if I enter things manually!
Thank you!
You just need to get Bank and Interest by names and use found model instances to get their ids to create InterestRate record:
async (req, res) => {
const bank = req.body.bank;
const type = req.body.type;
const nks = req.body.nks;
const eks = req.body.eks;
const time = req.body.time;
const foundBank = await Bank.findOne({
where: {
name: bank // use a real field name instead of "name"
}
})
const foundInterest = await Interest.findOne({
where: {
name: type // use a real field name instead of "name"
}
})
if(!foundBank) {
// here should be some "res.status(...).send(...)" with error message
return
}
if(!foundInterest) {
// here should be some "res.status(...).send(...)" with error message
return
}
try {
await InterestRate.create({
bankId: foundBank.id,
interId: foundInterest.id,
NKS: nks,
EKS: eks,
time: time,
})
res.status(200).json({ message: 'Added successfully' });
catch (err) {
res.status(500).send('Error -> ' + err);
}
};
Related
I have the following API to get the user's data based on a [pid]:
import prisma from "../../../../lib/prisma";
// Master read function - API route includes profile, subnodes and contents
async function getProfile(req, res) {
const profilePID = await prisma.profileNode.findUnique({
where: {
userName: req.query.pid
},
include: {
subnode: {
include: {
content: true,
}
},
},
})
// Integer for how many accounts the current user is following
const followingCount = await prisma.follower.count({
where: {
followerId: profilePID.userId
},
select: {
profileId: true
}
})
// integer for how many accounts the current user is being followed
const followerCount = await prisma.follower.count({
where: {
profileId: profilePID.userId
},
select: {
profileId: true
}
})
// detailed profile info of the people you are following
const following = await prisma.follower.findMany({
where: {
followerId: profilePID.userId,
NOT: {
profileId: null,
}
},
include: {
followees: true
}
})
// aggregate all data queries into one
const aggregatedData = {
profilesYouAreFollowing: followingCount.profileId,
yourProfileFollowers: followerCount.profileId,
followingData: following,
profileData: profilePID
}
if (aggregatedData) {
res.status(200).json(aggregatedData)
} else {
return res.status(500).json({ error: 'Something went wrong' })
}
}
export default async function handler(req, res) {
// commit to the database
if (req.method === 'GET') {
return getProfile(req, res)
}
}
As you would observe, the first request is to find the profileNode using a [pid] - which is a string like localhost:3000/user/ABC. Then I would get the userId (an integer) within the profileNode. The userId is then used in the rest of the prisma query to the database for followers and followers' details since all the ids are stored as integer.
I used SWR for client-side fetch, which is all fine but I noticed that while fetching, it will cause an error 500 before the data is fully fetched.
Now, while this does not hinder data fetching for presenting data to the client since SWR takes care of error handling and continue fetching until all the data is acquired, however, it does throw an error on other code like JSON.parse, as the error 500 has passed an undefined value to it - thus throwing an error.
Any tips or tricks as to how to get rid of the error 500?
Added client side code below:
const { data, error } = useSWR(`/api/profiles/read/${slug}`, fetcher)
const [subnodes, setSubnodes] = useState();
// authentication using next-auth session and fetched client-side userId
// compare equality - if equal, set Auth to true and show edit components
useEffect(() => {
async function fetchingData() {
setLoading(true);
// session
const session = await getSession();
let sessionUserId;
if (!session) {
sessionUserId = null;
} else {
sessionUserId = session.user.id;
}
// client
const clientId = await data?.profileData.userId;
// authentication check
if (sessionUserId !== clientId) {
setAuth(false);
} else {
setAuth(true);
}
async function asyncStringify(str) {
return JSON.parse(JSON.stringify(str));
}
const awaitJson = await asyncStringify(data?.profileData.subnode)
setSubnodes(awaitJson);
setLoading(false)
}
fetchingData();
}, []);
I am trying to retrieve the Id value of a freshly Inserted row in Mysql with react Axios.
Here Is my code In node.js
app.post('/createProject', (req,res) => {
const projectName = req.body.projectName;
const tjm = req.body.tjm;
const status = req.body.status;
db.query("INSERT INTO projects (projectName, tjm, status) VALUES (?,?,?)",
[projectName, tjm, status],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send("Values Inserted");
res.send(result.insertId);
console.log(result.insertId);
}
}
);
});
I try to get the insertId with a UseState hook;to use It in another Post request and store It in another table.
The post request In react:
const [id, setId] = useState();
const addProject = () => {
Axios.post("http://localhost:3001/createProject", {
projectName: projectName,
tjm: tjm,
status: "Inachevé"//Uncomplete,
}).then((res) => {
console.log("success");
setId(res.data);
});
};
I try console.log(id) but I get undefined in the console.
The post request to get the Inserted Id of the project:
const addWork = () => {
Axios.post("http://localhost:3001/createWork", {
EmpID: id_e,//I get that Id from a drop-down list
PrID: id_p,// the Id of the Inserted project who I can't get
}).then(() => {
console.log("success");
});
};
When I fill my Inputs In the frontend and send the the data (prjectName,tjm & status),the data is stored normally and the insertId consoled In the backend but I can't get it in my client side.
How I can access to insertId in the frontend and store It In another table at the same time when creating a new Project?
note: I think that I should use async/await to make addWork function wait until addProject execute but the probleme Is how to get the insertId In the frontend.
You should not use res.send() twice. You would probably want to send json, which works like the following: res.status(200).json({message: "Message",data: lastInsertedID}).
You would then need to make sure to correctly access the id in the frontend. Therefore you can print the whole json response object from on the console and make your way through the json object until you reach the id.
I am using postman to send a request and I see Success message but in the database, it's not updated at all.
PostMAN request
database Snap shot
update services object: from this file I have used a database query to insert data in the database and set callBack funtion
const pool = require('../../config/database')
module.exports = {
updateUser: (data, callBack) => {
pool.query(
`UPDATE users SET firstName=?,email=?,password=?,lastName=?,phoneNumber=?, sex=? WHERE id=?`, [
data.firstName,
data.email,
data.password,
data.lastName,
data.phoneNumber,
data.sex,
data.id
], (error, results, fields) => {
if (error) {
return callBack(error)
}
return callBack(null, results)
}
)
}
}
update user controller here I have added a controller to update the user details which receive the data from update user services.
const {
create,
getUserbyID,
getUsers,
updateUser,
deleteUser,
getUserByEmail
} = require('./userService')
const {genSaltSync, hashSync, compareSync} = require('bcrypt')
const { sign } = require('jsonwebtoken')
module.exports ={
updateUser: (req, res) => {
const body = req.body;
const salt = genSaltSync(10);
body.password = hashSync(body.password, salt);
updateUser(body, (err, results) => {
if (err) {
console.log(err)
return false;
} // added
console.log("this is the body: "+JSON.stringify(req.body))
console.log("this is the results: "+ JSON.stringify(results))
if (!results) {
return res.json({
success:0,
message: "failed to update user"
})
}
return res.json({
success: 1,
message: "Updated Sucessfully"
})
})
},
}
router.js
router.patch('/update',checkToken, updateUser)
ADDED console.log
this is the body: {"Id":15,"firstName":"joey","email":"joey.chandler357#gmail.com","password":"$2b$10$ZBnRppSKAfQ1TrzGvs/wqOrVx/shb6ESJ7emXnC7IlWRN3VUGgfK2","lastName":"chandler","phoneNumber":"9860316634","sex":"Male"}
this is the results: {"fieldCount":0,"affectedRows":0,"insertId":0,"serverStatus":2,"warningCount":0,"message":"","protocol41":true,"changedRows":0}
I can see your console.log message
this is the results: {"fieldCount":0,"affectedRows":0,"insertId":0,"serverStatus":2,"warningCount":0,"message":"","protocol41":true,"changedRows":0}
Here you can notice affectedRows: 0 it means no row updated this happens when condition is not matched with any of the records. In postman you are passing "Id" I is in capital format but at the time of accessing this in service you are using "data.id" id is small latter so this is creating problem
we can handle this
instead of
if (!results) {
return res.json({
success:0,
message: "failed to update user"
})
}
use
if (!results.affectedRows) {
return res.json({
success:0,
message: "failed to update user"
})
}
this will be much better then previous check
I think you need to use an "insert" to add the db record. It's using an update... so it's looking for a pre-existing record.
Try two things:
wrap “users” in quotes on your update query. I’ve seen this w Postgres where some words are reserved in raw queries.
Examine the database response from your update. See what is console logged.
Promise newbie here.
I'm trying to retrieve icon_name field from asset database, Equipment table in mongodb
and update icon_id field in equipments database, equipments table in mysql.
I have about 12,000 records with icon_name field in Equipment.
The script runs successfully however it doesn't seem to go through all the records.
When I check the equipments table there are only about 3,000 records updated.
I tried running the script several times and it appears to update a few more records each time.
My suspicion is the database connection is close before all the queries are finished but since I use Promise.all I don't know why it happened.
Here is the script
const _ = require('lodash'),
debug = require('debug')('update'),
Promise = require('bluebird')
const asset = require('../models/asset'),
equipments = require('../models/equipments')
const Equipment = asset.getEquipment(),
my_equipments = equipments.get_equipments(),
icons = equipments.get_icons()
Promise.resolve()
.then(() => {
debug('Retrieve asset equipments, icons')
return Promise.all([
icons.findAll(),
Equipment.find({ icon_name: { $ne: null } })
])
})
.then(([my_icons, asset_equipments]) => {
debug('Update equipments')
const updates = []
console.log(asset_equipments.length)
asset_equipments.forEach((aeq, i) => {
const icon_id = my_icons.find(icon => icon.name === aeq.icon_name).id
up = my_equipments.update(
{ icon_id },
{ where: { code: aeq.eq_id } }
)
updates.push(up)
})
return Promise.all(updates)
})
.then(() => {
debug('Success: all done')
asset.close()
equipments.close()
})
.catch(err => {
debug('Error:', err)
asset.close()
equipments.close()
})
Thanks in advance.
Code looks fine but spawning 12000 promises in parallel might cause some trouble on the database connection level. I would suggest to batch the concurrent requests and limit them to let's say 100. You could use batch-promises (https://www.npmjs.com/package/batch-promises)
Basically something like
return batchPromises(100, asset_equipments, aeq => {
const icon_id = my_icons.find(icon => icon.name === aeq.icon_name).id;
return my_equipments.update({ icon_id }, { where: { code: aeq.eq_id } });
});
In mysql table i have created, I set autoincrement and unique value for the primary key. It is
I ran the following code multiple times. it is suppose to show error most of the time due to repetitive keys entered, however, there was no error.
exports.handler = async (event) => {
var mysql = require('mysql');
// TODO implement
var connection = mysql.createConnection({
host : '-',
user : '-',
password : '-',
database : '-'
});
const sql = `INSERT INTO forms VALUES(20,2,4,4,5,6,7,8,9,10,11);`;
connection.query(sql, (err, res) => {
if (err) {
throw err
}
})
const wait = () => {
setTimeout(()=>console.log('timeout'),2000)
}
await wait();
await console.log(sql)
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
It is suppose to show error as below
But it shows no error most of the time.Why?