I am trying to write an application with Node.js & PostgreSQL, currently I faced a problem in get by id, below is my code
app.get('/monsters/:id', (request, response, next) => {
const { id } = req.params;
pool.query('select * from monsters where id = $1', [id], (err, res) => {
if (err) {
return next(err);
}else {
response.json(res.rows);
}
});
});
it supposed to get the id I typed and return the value I stored in database with a table name called monster, however it just kept returning a blank object {}, I found the problem may because of the $1 part since my atom seemed not able to recognize $, what can I do to fix this problem or is there other way to write this instruction? Thank you!
Related
I'm doing a project on an e-commerce website. here I'm with a problem.
I have used the get method to retrieve user data from MongoDB
I have passed the correct parameters and the statement UserId:req.params.userId has been satisfied where we can see in the nodejs terminal.
I'm looking to get only particular user data with UserId === UserId. But in my result, all the user's data is popping up.
Im trying this but the solution im getting is all the users data
i have tried using findOne() but the result is this 635ea7e5e931e12c9f851dd3 user details. where the parameter is 63a8a0f77addf42592eed1e5. where im expecting to get the only user which im passing in parameter.
router.get("/find/:userId", verifyTokenAndAuthorization, async (req, res) => {
try {
const cart = await Cart.find(
{userId : req.params.userId});
console.log("parameter: "+req.params.userId)
return res.status(200).json(cart);
} catch (err) {
res.status(500).json(err);
}
The req.params userId is '63a8a0f77addf42592eed1e5'. i need only this. but it is popping up all the users data.
Node.js terminal showing the parameter is same with userId
Postman showing the response of all users present in the DB but i need only the user details which i had passed in the parameter
Here the mongoDB find method returns all data in the collection, irrespective of the parameters that we pass in to it. Instead try using the findOne method for that collection. So the code with correction will be as follows:
router.get("/find/:userId", verifyTokenAndAuthorization, async (req, res) => {
try {
const cart = await Cart.findOne(
{userId : req.params.userId});
console.log("parameter: "+req.params.userId)
return res.status(200).json(cart);
} catch (err) {
res.status(500).json(err);
}
You can read more about the method at MongoDB Manual.
I had found the solution for my problem i.e I have used filter method at (res(200).json(cart.filter(((user)=>user.UserId === req.params.userId))
This means
Using filter method UserId in my model === to the parameters userId
router.get("/find/:userId", verifyTokenAndAuthorization, async (req, res) => {
try {
const cart = await Cart.find(
{userId : req.params.userId});
console.log("parameter: "+req.params.userId)
res.status(200).json(cart.filter((user)=>user.UserId === req.params.userId));
console.log(cart.filter((user)=>user.UserId === req.params.userId))
} catch (err) {
res.status(500).json(err);
}
});
Hi. I am looking to create a reusable query with MySQL and NodeJS
The first step I took after the DB connection was to create a data access object and interact with the DB while using promises. To stay relative secure, I am using placeholders:
" ? " for rows and values and double " ?? " for tables.
I want to create functions to be reused. So if I am creating one function for insert, I need to use same function to insert records in different tables while using parameters.
The Data access layer looks like this: Here I am using parameters that will go to each function and replace the placeholders from the sql statements.
/*
Insert user accepts three parameters. Statement from mysql, table marked with ?? in the statement and the
payload object that have to match the database columns
*/
insertRecord: (sqlStatement, table, payload) => {
return new Promise((resolve, reject) => {
db.query(sqlStatement, [table, payload], (error, response) => {
if (error) return reject(error);
return resolve(response);
});
});
},
/*
This function accepts four parametters. The first parameter is the statement. Second parameter is the table selector
marked with ?? in the statement.
The selector is the row, and the value specified
*/
selectSimpleStatement: (sqlStatement, table, row, value) => {
return new Promise((resolve, reject) => {
db.query(sqlStatement, [table, row, value], (error, response) => {
if (error) return reject(error);
else return resolve(response);
});
});
}
}
The second implementation was to create all the MySQL queries separately because I wanted to keep it Clean
module.exports = {
insertStatement: 'INSERT INTO ?? SET ?',
sqlSimpleSelect: 'SELECT * FROM ?? WHERE ? = ?'
}
Using the first sql statement was easy. I worked to insert in all the tables with the same function. But the select is a pain. With postman I am getting empty arrays even if the values are correct...
const { sqlSimpleSelect } = require('../../database/statements.js');
const bcrypt = require('bcrypt');
exports.add = async (req, res, next) => {
const {username, password} = req.body;
try {
// Select from users where username = username variable
const user = await selectSimpleStatement(sqlSimpleSelect, 'users', 'username', username);
res.send(user);
}
catch (error) {
res.send(error)
}
}```
I am getting empty array. Can please help me?
Thanks, Daniel
I am calling this code from the front-end and confirmed that there is a proper db connection and that the Id value is properly passed, and that there is a corresponding value in the database, but for some reason, res is null. What am I missing?
app.get("/api/walletlogin/user/:userId", (req, res) => {
id = req.params.userId
var query = {_id: id}
db.collection("Users").findOne(query, (err, result) => {
if (result) {
console.log(result.userName)
} else {
console.log('No User')
}
})
Here is the front-end call:
axios.get('/api/walletlogin/user/' + accounts)
.then((response) => {
console.log('Logged in With ' + accounts)
router.push('/account')
})
.catch((errors) => {
console.log('Cannot log in')
})
}).catch((err) => {
console.log(err, 'err!!')
})
You could try to convert your id to an objectID.
var ObjectId = require('mongodb').ObjectId;
var id = ObjectId(req.params.userId);
to search by id, you must use the ObjectID class from the mongodb package. Here is an example invented by me, it does not reflect the real work, but I hope it will become clear on it:
const { ObjectID } = require('mongodb');
const id = '5ee4f69bfa0b960de8aec158'; // in your example is req.params.userId
db.collection('users').findOne({ _id: new ObjectID(id)}, (error, result) => {
if (error) {
throw error;
}
console.log(result);
})
I am adding the details of the issue initially encountered in case someone else would experience it in the future. The value that is passed from the front-end is a cryptocurrency address. For some reason, some of the characters passed were upper-case, while the same address had been stored in the database with these same characters as lower case. Thus, one needs to add code to make sure that the case of the letters found in the respective addresses is ignored.
J
I am new to node js programming and trying to develop an API using node js, I am able to retrieve the expected output from the built API but I would like to perform some exception handling. For that I would like to check whether the request params coming from URL are not null. Below is my code:
async function getDetails(input) {
// using knex to execute query
return queries.getbymultiwhere('table_name',{
name:input.name,
id:input.id,
role:input.role
})
}
router.get('/:name/:id/:role',(req,res)=>{
getDetails({
name:req.params.name,
id:req.params.id,
role:req.params.role}).then(Results=>{ Do something with results}
})
In above code I want to check that name, id and role param values are not null.
Any helpful solution will be appreciated.
Thank you!
You can create a middleware which checks those parameters.
function check(fields) {
return (req, res, next) => {
const fails = [];
for(const field of fields) {
if(!req.query[field]) {
fails.push(field);
}
}
if(fails.length > 0){
res.status(400).send(`${fails.join(',')} required`);
}else{
next();
}
};
}
app.get('/api', check(['name', 'id', 'role']), (req, res) => {
getDetails()...
});
This is my first attempt at deleting data in a MongoDB database. I'm loosely following this tutorial (just the delete part) to no avail, https://www.airpair.com/javascript/complete-expressjs-nodejs-mongodb-crud-skeleton. I just want to delete all the requested people who are in the requested country. All of my other requests work so I will just post the code that I know is not working, everything else is fine.
EDIT
The error I get in the log is "404 Not Found". When testing w/ Postman the response I get is, "Cannot DELETE /deletepeople/USA/John"
app.delete('deletepeople/:country/:name', function(req, res) {
var countryReq = req.params.country;
var nameReq = req.params.name;
peopleModel
.find({"country":countryReq}, function(err, country) {
country.find({"name": nameReq}, function (err, person) {
person.remove(function (err, person) {
if (err) {
console.log(err);
res.status(500).send();
}
return res.status(200).send();
})
})
})
});
});
country.find({"name": nameReq}, function (err, person) {
The above line is causing you an error, what are you searching in a returned document? Its just an document and not a collection.
You can use the id() method in embedded docs:
Look at the subdocuments [http://mongoosejs.com/docs/subdocs.html]