I have a question how do I post two similar columns, I tried sending it with array using for of cause I'm using async/await and when I only post one column it works perfectly, but it doesn't when it has two similar columns, any information would really help me
here are my models
postItems: function (setData) {
return new Promise((resolve, reject) => {
db.query('INSERT INTO datas (picture, name, price, quantity, delivery_on, data_description) VALUES (?, ?, ?, ?, ?, ?)', [setData.picture, setData.name, setData.price, setData.quantity, setData.delivery_on, setData.data_description], function (err, res) {
if (!err) {
resolve(res)
} else {
reject(err)
}
})
})
}
postItemsToItemCategory: function (setData) {
return new Promise((resolve, reject) => {
db.query('INSERT INTO data_categories ( data_id, category_id) VALUES (?, ?)', [setData.data_id, setData.category_id], function (err, res) {
if (!err) {
resolve(res)
} else {
reject(err)
}
})
})
}
and here's my controller
postItemData: async function (req, res) {
const setData = req.body
try {
if (setData.price < 1) {
return helper.response(res, 'fail', 'Cannot type number below 1', 400)
}
const result = await itemModels.postItems(setData)
const categoryData = {
data_id: result.insertId,
category_id: setData.category_id
}
if (typeof categoryData.category_id !== 'object') {
categoryData.category_id = [categoryData.category_id]
}
for (const category of [categoryData]) {
try {
console.log(categoryData)
await postItemsToItemCategory(category)
console.log(`product ${result.insertId} has been created on category ${setData.category_id}!`)
} catch (err) {
console.log(err)
}
}
return helper.response(res, 'success', result, 200)
} catch (err) {
console.log(err)
return helper.response(res, 'fail', 'Internal Server Error!', 500)
}
}
I fixed my code, so if anyone needs it maybe it will help
//model
postItemsToItemCategory: function (setData, cb) {
db.query('INSERT INTO data_categories ( data_id, category_id) VALUES (?, ?)', [setData.data_id, setData.category_id], cb)
}
and I found the problem I'm not careful to not put the await and change the for of into forEach
postItemData: async function (req, res) {
const setData = req.body
try {
if (setData.price < 1) {
return helper.response(res, 'fail', 'Cannot type number below 1', 400)
}
const result = await itemModels.postItems(setData)
if (typeof setData.category_id !== 'object') {
setData.category_id = [setData.category_id]
}
await setData.category_id.forEach((categoryId) => {
const categoryData = {
data_id: result.insertId,
category_id: categoryId
}
postItemsToItemCategory(categoryData, () => {
console.log(`product ${result.insertId} has been created on category ${categoryId}!`)
})
})
return helper.response(res, 'success', result, 200)
} catch (err) {
console.log(err)
return helper.response(res, 'fail', 'Internal Server Error!', 500)
}
}
Related
How to pass id in where clause using node.js and MySQL?
Viewer.jsx
async function redeem(cid) {
fetch('http://localhost:4000/getDetailsFromCid/${cid}').then(response => {
return response.json()
})
.then(posts => {
console.log("posts", posts)
})
.then((err) => {
console.log(err);
})
}
index.js
app.get("/api/getDetailsFromCid/:cid", (req, res) => {
const cid = req.params.cid;
db.query("SELECT * FROM Details WHERE cid = ?", [cid],
(err, result) => {
if (err) {
console.log(err)
}
res.send(result)
});
});
Error
Viewer.jsx:19 GET http://localhost:4000/getDetailsFromCid/$%7Bcid%7D 404 (Not Found)
you need to use `` not ''
fetch(`http://localhost:4000/getDetailsFromCid/${cid}`)
As the name states, I keep getting a "Query was already executed" while running Mongoose.find queries. Using '.clone' does not seem to be fixing the issue...
My calling code is:
let result = mongo.isValidUsername(req.body.username).then((data) => {
return data;
});
if ((await result) == false) {
res.send("Sorry, that username is unavailable");
} else {
mongo
.addUser(
req.body.username,
req.body.password,
req.body.firstName,
req.body.lastName,
req.body.email,
req.body.phoneNumber
)
.then(() => {
let profileData = mongo.getProfileData(req.body.username);
profileData
.then((data) => {
res.render("accountDisplay", {
results: data,
trans: [9.99],
});
})
.catch((err) => {
console.log(err);
});
});
}
I call a query twice - Once in isValidUsername() at the beginning (where I have not used .clone) and then again in getProfileData( where I HAVE used .clone).
I keep getting this error. Any idea what could be causing it?
Here is the code for isValidUsername() and getProfileData(), just in case...
async function isValidUsername(usernameToQuery) {
//connect to mongoose database
mongoose.connect("mongodb://localhost:27017/bankDB");
try {
let isValid = UserModel.findOne({ username: usernameToQuery }).then(
(data) => {
if (data == null) {
return true;
} else {
return false;
}
}
);
return await isValid;
} catch (err) {
return err;
}
}
async function getProfileData(usernameToQuery) {
mongoose.connect("mongodb://localhost:27017/bankDB");
let profileData = UserModel.findOne({ username: usernameToQuery }).clone();
console.log(await profileData);
let profileArray = await profileData.then((data) => {
return [
data._doc.firstName,
data._doc.lastName,
data._doc.email,
data._doc.phoneNumber,
];
});
return await profileArray;
}
I tried without success, to execute my Promise with Sequelize on stored procedure(MSSQL) inside the function, below the code (when I don´t use the Promise, this code runs perfectly, retrieving the json´s data):
function getData(numTravessia) {
return new Promise((resolve, reject) => {
return connection.query(
'EXEC [dbo].[SP_RECUPERAINFOTRAVESSIA] #ID=:param1',
{
replacements: {
param1: numTravessia,
},
type: QueryTypes.SELECT
},
(error, meta, body) => {
if (body != undefined) {
resolve(body.toString());
} else {
reject(error);
}
})
});
}
async function getInfoTravessia(numTravessia) {
try {
var r = await getData(numTravessia);
return JSON.parse(r);;
} catch (error) {
console.log(error);
}
}
app.listen(8000, () => {
console.log("aplicativo em execução");
getInfoTravessia(1955).then((result) => {
console.log(result);
}).catch((e) => {
console.log(e);
})
});
Below, follow the code snippet that I don´t use the Promise and it´s working:
connection.query(
'EXEC [dbo].[SP_RECUPERAINFOTRAVESSIA] #ID=:param1',
{
replacements: {
param1: 1955,
},
type: QueryTypes.SELECT
}).then((result) => {
// RETORNA UM STRING
var obj = result[0];
res.send(obj);
// return obj;
}).catch((e) => {
console.log('error', e);
});
Please, anyone can help me?
I'm trying to translate my old mysql app to Postgresql, it was very difficult to connect to the server, but when i think it worked, this message appears on insomnia.
The message
I tried using different methods that i found on Google but they didn't work for me.
I think that the problem is how i'm connecting to the server.
I'm new using postgresql.
const { Pool, Client } = require("pg")
const config = require("../config")
const connection = new Pool({
host: config.postgresql.host,
user: config.postgresql.user,
password: config.postgresql.password,
database: config.postgresql.database,
port: "5432",
ssl: true
})
function list(table) {
return new Promise((resolve, reject) => {
connection.query(`SELECT * FROM ${table}`, (err, data) => {
if (err) return reject(err)
resolve(data)
})
})
}
function get(table, id) {
return new Promise((resolve, reject) => {
connection.query(`SELECT * FROM ${table} WHERE id=${id}`, (err, data) => {
if (err) return reject(err)
resolve(data)
})
})
}
function insert(table, data) {
return new Promise((resolve, reject) => {
connection.query(`INSERT INTO ${table} SET ${data}`, (err, result) => {
if (err) return reject(err)
resolve(result)
})
})
}
function update(table, data) {
return new Promise((resolve, reject) => {
connection.query(
`UPDATE ${table} SET ${data} WHERE id=${data.id}`,
(err, result) => {
if (err) return reject(err)
resolve(result)
}
)
})
}
const upsert = async (table, payload) =>
new Promise((resolve, reject) => {
connection.query(
`INSERT INTO ${table} SET ${payload} ON DUPLICATE KEY UPDATE ${payload}`,
(error, data) => {
console.log("UPDATE DATA: ", data)
if (error) {
return reject(error)
}
resolve(data)
}
)
})
function query(table, query, join) {
let joinQuery = ""
if (join) {
const key = Object.keys(join)[0]
const val = join[key]
joinQuery = `JOIN ${key} ON ${table}.${val} = ${key}.id`
}
return new Promise((resolve, reject) => {
connection.query(
`SELECT * FROM ${table} ${joinQuery} WHERE ${table}.${query}`,
(err, res) => {
if (err) return reject(err)
resolve(res[0] || null)
}
)
})
}
module.exports = {
list,
get,
upsert,
query
}
The insert query is wrong, Please change it to the below syntax. You cannot use SET in insert. SET should be used in update.
Wrong:
connection.query(`INSERT INTO ${table} SET ${data}`, (err, result)
Insert query syntax:
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
I have created a function that is looking for any reservation document with matching _id, if exists is deleted, and next the Book(findById) function is performed which is looking for any books using function(findOneAndUpdate), if exists is added value to quantity +1.But i don't know why but the function does not want to be done.
router.post('/cancel-reservation', (req, res) => {
var reservation = req.body.reservation;
Reservation.findByIdAndRemove(reservation._id, function (err) {
if (err) throw err;
else {
Book.findById(reservation.idBook, (err, book) => {
if (err) throw err;
if (book == null) {
//////////// //*WORKING *////////////////
let bookObj = {
name: reservation.nameBook,
description: reservation.description,
publishingHouse: reservation.publishingHouse,
quantity: 1,
year: reservation.year,
sites: reservation.sites
};
var book = new Book(bookObj);
book.save()
.then(function (book) {
res.json(book)
})
.catch((err) => {
res.json('not saved')
})
//////////// //*WORKING *////////////////
} else if (book) {
// findOneAndUpdate
//////////// //*HERE IS PROBLEM *////////////////
book.quantity = book.quantity+1;
console.log(book._id)
Book.findOneAndUpdate({ _id: book._id },
{ $set: { quantity : book.quantity } }, { upsert: true }),
((err, complete) => {
if(err) console.log('errrrrr');
else {
console.log(complete)
console.log('complete')
res.json(complete)
}
})
}
});
}
});
});
this problem may be related to the fact that the findOneAndUpdate function is nested in findById?
I think that you have an extra parentheses on the findOneAndUpdate
Book.findOneAndUpdate({ _id: book._id },
{ $set: { quantity : book.quantity } }, { upsert: true },
(err, complete) => {
if(err) console.log('errrrrr');
else {
console.log(complete)
console.log('complete')
res.json(complete)
}
})