i am working on a task where i am workking on create user. i am taking the inputs from the postman and i am validating all the fields and when ever all are validated correctly i am going to insert it in the database.. i am using mongo db as database. But whats the problem is i am taking inputs as first name ,lastname,userid and password and confirm password .. but when i am inserting it the connfirm password also inserting .. so i need to remove that particular field .
mongo.get().collection("customers").insertOne(req.body, function(err, res) {
if (err) throw err;
});
where mongo.get() is the database connection url
Well you can delete that property from your document/object before inserting into database.
Something like
delete req.body.confirmPasswordFiled
mongo.get().collection("customers").insertOne(req.body, function(err, res) {
if (err) throw err;
});
Related
I am building an application that has a backend that uses SQL queries to get data from a SQL Server database. However, I need to write a query that truncates and repopulates a table in that database using data from a second database. Here is what my code looks like:
// establishes a connection to serverName and uses DB1 as the database. But how can you access two?
global.config = {
user: 'username',
password: 'password',
server: 'serverName',
database: 'DB1'
};
// run this query. It's already been tested in SQL server and works fine there
let query = "TRUNCATE TABLE [DB1].[dbo].[Shop]; INSERT INTO [DB1].[dbo].[Shop] (Shop, shopDescription, Address, City)" +
" SELECT Shop, Description, Address, City FROM [DB2].[dbo].[ShopTable]"
new sql.ConnectionPool(config).connect().then(pool => {
return pool.request().query(query) }).then(
result => {
console.log(result.recordset)
//result returns as "undefined"
res.setHeader('Access-Control-Allow-Origin', '*')
res.status(200);
sql.close();
}).catch(err => { //error is not thrown
res.status(500).send({ message: err})
sql.close();
});
I get an "undefined" result, and find that no update to the table was made. The issue here isn't exactly clear whether it can't reach the table in DB2, or if perhaps the command doesn't work with the Node.js mssql package?
It appears this was a front end to back end connection issue. I was able to get the query to work without any changes to the database information, so it appears I can access the second database without any issues.
component.ts
this.httpService.patch('update', {} ).subscribe()
index.js
app.patch('/api/update', controllers.manualQueries.update);
Within my view, I am directing the user from '/dashboard' to '/upvote'
Within my routes, I have:
app.get('/upvote', function(req, res) {
user = req.user
user.score += 1;
user.save();
res.redirect('/dashboard');
});
This is just an example, trying to grasp how to use this for a different purpose at a later stage.
How do I correctly update my users 'score' attribute to increment every time there's a GET command for '/upvote/' ?
You need to find the given user in your request; req.user is just an object and not a mongoose model. If you have the ID of the document, you can use findById. If you don't you'll need to use a find query on another field.
// Users is the mongoose model
Users.findById(id, function (err, user) {
if (err) return handleError(err);
user.score += 1;
user.save(function(err) {
if (err) return handleError(err);
res.send(user); // Or redirect, basically finish request.
});
});
Second of all - I wouldn't necessarily do a redirect. You could stay on the same page and simply have the command refresh the user model.
If you separately modify and then save your user document, you can lose votes during concurrent requests.
Instead, use update with the $inc operator to make the upvote atomic:
app.get('/upvote', function(req, res) {
User.update({_id: req.user._id}, {$inc: {score: 1}}, function(err, count) {
res.redirect('/dashboard');
});
});
BTW, you should consider using a POST or PUT request instead of a GET as GET requests shouldn't change data.
When i run my node.js script i get this error:
http://i.gyazo.com/4abc4f518db0de3cb36e34a9fa163e22.png
I was reading a similar error and the guy said it was because the script wasn't connecting to the mysql database. I've tried all of the different logins i can think of and it still wont work. I have tried connecting with no credentials and i get the same error. These are the current credentials i am using to log in:
host : 'localhost',
user : 'root',
password : 'mypassword',
database : 'milky',
The code where the error comes from:
mysqlConnection.query('SELECT `value` FROM `info` WHERE `name`=\'maxitems\'', function(err, row, fields) {
if(offer.items_to_receive.length > row[0].value) {
offers.declineOffer({tradeOfferId: offer.tradeofferid});
offer.items_to_receive = [];
mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`) VALUES (\''+offer.steamid_other+'\',\'toomuch\',\'System\')', function(err, row, fields) {});
return;
I am trying to read the SQL query output in javascript
I am using Node.js , Express Engine (a MVC model) to read the MySQL database and display the output on UI using Jade.
I have a file index.js which fetches value of 'password' and 'user_name'from homepage.jade form field.
I have to check if the password entered by user matches the password in the database.
for which I am querying the database to get a matching record for the entered username and want to fetch the password value for that user and check if it is equal to the form value of password.
router.get('/sample', function(req, res) {
db=mysql.createConnection(config);
db.connect(function(err){
});
var formpass= req.body.password;
var user_name= req.body.userName;
var sql="select * from user where user_name= 'monicathaneer'";
db.query(sql, function(err_query,data)
{
for a in data
pass= a.password;
}
if(formpass==pass)
{
res.render('Login', {
"Login" : data });
}
});
I get errors saying unexpected token near 'a' and unexpected token near 'if' when I run the node.
I would like to know how can I can read the password property from the sql output in a .js file.
Your code sample has some syntax errors and lost curly braces. Try this (assuming you're using node-mysql module):
router.get('/sample', function(req, res) {
var formpass = req.body.password,
user_name = req.body.userName,
sql = "select * from user where user_name = 'monicathaneer'";
var db = mysql.createConnection(config);
db.connect(function (err) {
// you should handle the errors here
});
db.query(sql, function (err_query, data) {
// I'm assuming your query will return just 1 row
// because usernames should be unique
if (formpass === data[0].password) {
res.render(
'Login',
{"Login": data}); // In your context, 'data' contains the user password...
// Do you really want to send it back to the web page?
}
});
db.end(); // you forgot to close your connection.
});
Some considerations:
You should not try to handle authentication manually. Consider using a middleware like Passport.js;
You don't need to open and close your connection on each request. Try to refactor your code in order to open the connection when the app starts, and use it on demand.
I am using Express.js to build a small application. I have successfully implement the feature that allows me to add new entries to the database.
I am currently trying to delete an entry from a mysql db when a user clicks on a button. This is the code that gets executed:
client.query('DELETE FROM humans WHERE id= ?', [req.params.id], function(err, result) {
if (err) {
throw err;
}
res.redirect('/humans');
I know that the code executes properly because I get redirected to the correct page. Still, my entry is still in the database.
Deducing from the comments to your question I guess that you're sending the id from a form using a POST request. To find post params in req.body (if you're using the express.bodyParser middleware). Thus:
client.query('DELETE FROM humans WHERE id= ?', [req.body.id], function(err, result) {
if (err) {
throw err;
}
res.redirect('/humans');
});
If you're sending a GET request the param would be find in req.query.