How to compare input and Document in mongoDB - node.js

When I Register [ input Email / password to DB ] success. Then, I want to login. If input[email/pass] == document in collection >> go to next page, else console.log['wrong email/pass']
I try to wirte IF/else code but I don't know check condition.
This code is Register form
app.post('/register',function(req,res){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
let dbo = db.db("project");
let myobj = { Email: req.body.email, Password: req.body.psw } ;
dbo.collection("Register").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log(" document inserted");
db.close();
});
});
});
This code is Login form
app.post('/index',function(req,res){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
let dbo = db.db("project");
let cursor = dbo.collection('Register').find();
cursor.each(function(err,doc) {
if (doc == req.body.email && req.body.psw){
console.log("goto next page");
}
else{
console.log('wrong');
}
});
db.close();
});
});
Correct input and wrong input Output is = Wrong
Pls insert loop check all of array pls.
app.post('/index',function(req,res){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("project");
dbo.collection("Register").findOne({}, function(err, result) {
if (result.Email == req.body.email && result.Password == req.body.psw) {
console.log("OK");
}
else{
console.log(result.Email && result.Password);
}
db.close();
});
});
});

You have to compare individual values, like so:
if (doc.Email == req.body.email && doc.Password == req.body.psw){
console.log("goto next page");
}

Firstly you should check for valid request body and the you should do a fineone query instead of running a for-loop and checking. see the corrected one below :
app.post("/index", function(req, res) {
let {
email,
psw
} = req.body;
if (email && psw) {
console.log("wrong credentials");
return;
} else {
MongoClient.connect(url, function(err, db) {
if (err) throw err;
let dbo = db.db("project");
let data = dbo.collection("Register").findOne({
Email: email,
Password: psw
});
if (data) {
console.log("goto next page");
} else {
console.log("wrong");
}
db.close();
});
}
});

I'm late to the party but I just found a solution to a similar problem and wanted to share.
If you have input values in javascript and want to use them in a mongodb query you need to make them in to strings.
Assuming user._id is a value coming from a javascript function call.
This will work:
{ userId: { $eq: ${user._id} } } ✅
This won't work:
{ userId: { $eq: user._id } } ❌

Related

Return 404 in MongoDB block

I use follow codes to insert something into mongodb, and if it is successfully insertted, I should get string with information success
if (email) {
MongoClient.connect(dbUrl, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
const dbo = db.db("email");
const dbObj = {email: email};
dbo.collection("email").insertOne(dbObj, function(err, res) {
if (err) throw err;
ctx.body = "success";
db.close();
});
});
} else {
ctx.body = "email is missing";
}
And now the document can be inserted into mongodb, but the get 404 Not Found, any ideas?

Finish execution if first query returns a value Node.js Express.js mongoDB

Before starting, please mind that i have been searching this over 2+ hours, the answer will be simple i know but i couldnt get it to work . i am new to express node mongodb,
MongoClient.connect(url, function(err, db) {
if (err) {
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
}
var usernameGiven = req.body.usernameGiven;
//Select the database
var dbo = db.db("notifellow");
//run the query
var query = { username: usernameGiven , friends: []};
dbo.collection("users").findOne({ username: usernameGiven}, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
console.log("Query Error Occured!");
}
else {
if (result) {
//Send the response
res.send("EXISTS");
//I WOULD LIKE TO EXIT IF THIS LINE EXECUTES
}
}
});
dbo.collection("users").insertOne(query, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
console.log("Query Error Occured!");
}
else {
if (result) {
//Send the response
res.send("CREATED 201");
} else {
res.send("Failed to insert");
}
}
});
db.close();
});
my goal is to check if an user doesnt exists with given username, i would like to insert that to the DB.
i would like to exit if my query finds an match and arrange such that insertOne wont execute. please enlighten me!!
Once you are not using the async/await syntax you will have to nest the calls to MongoDB, so they execute in series. You can also use a module like async to achieve this.
MongoClient.connect(url, function(err, db) {
if (err) {
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
}
var usernameGiven = req.body.usernameGiven;
//Select the database
var dbo = db.db("notifellow");
//run the query
var query = { username: usernameGiven , friends: []};
dbo.collection("users").findOne({ username: usernameGiven}, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
db.close();
console.log("Query Error Occured!");
return res.send(err.message);
}
if (result) {
db.close();
return res.send("EXISTS");
}
dbo.collection("users").insertOne(query, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
db.close();
console.log("Query Error Occured!");
return res.send(err.message);
}
db.close();
if (result) {
return res.send("CREATED 201");
}
res.send("Failed to insert");
});
});
});
Try this
dbo.collection("users").findOne({ username: usernameGiven}, function(err, result) {
if (err){
//put the error logic
}
else {
if (result) {
//Send the response
return result;
}
else{
// if above if block fails it means that user does not exist
//put the insert logic
}
});

Send variables to layout

I'm learning how to build web applications using Node.js and express, so I'm really noob yet.
So, I have some questions here. I'm building a landing page, and all the informations that I'm getting from my Database (in mysql) will appear in a single page.
I'm sending values from my database, to my layout, built in Jade.
And I created multiple functions to get specific data, here an example:
function getUser(username, userId, callback) {
connection.query('SELECT * FROM users WHERE user_id = ?', userId, function(err, result) {
if (err)
callback(err, null);
else
var callBackString = {};
callBackString.value1 = result[0].user_email;
callBackString.value2 = result[0].user_name;
callback(null, callBackString);
});
}
When the user tries to login I check if the user exists to change the layout and send to the layout some important values:
router.post('/login', function(req, res) {
connection.query('SELECT user_id FROM users WHERE user_email = ? AND user_password = ?', [req.body.login, req.body.password], function(err, results) {
if (err) throw err;
if (results[0]) {
userId = results[0].user_id;
getUser("username", userId, function(err, data) {
if (err) {
console.log("ERROR : ", err);
} else {
res.render('logged_in', {
email: data.value1,
username: data.value2,
});
res.end();
}
});
} else {
res.render('index', {
validation: "failed"
});
}
});
});
I'm only calling one function here (getUser()), and when I call this function, the layout changes, and I send some values.
But now I would like to create a new function called getPosts(), to get informations from a different table, and send it to the layout too, like I did when i called the function getUser()
I tried to do something like this but I had no success, when I call the variables outside the scope I keep getting "undefined".
router.post('/login', function(req, res) {
connection.query('SELECT user_id FROM users WHERE user_email = ? AND user_password = ?', [req.body.login, req.body.password], function(err, results) {
if (err) throw err;
if (results[0]) {
userId = results[0].user_id;
getUser("username", userId, function(err, data) {
if (err) {
console.log("ERROR : ", err);
} else {
email = data.value1;
username = data.value2;
}
});
getPosts("posts", 1, function(err, data) {
if (err) {
console.log("ERROR : ", err);
} else {
postName = data.value1;
postText = data.value2;
}
});
res.render('logged_in', {
email: email,
username: username,
pstname: postName,
psttxt: postText
});
res.end();
} else {
res.render('index', {
validation: "failed"
});
}
});
});
What do I need to change on my code? Thank you.
You should read about asynchronization in node.js so if you change your code as bellow it may work:
router.post('/login', function(req, res) {
connection.query('SELECT user_id FROM users WHERE user_email = ? AND user_password = ?', [req.body.login, req.body.password], function(err, results) {
if (err) throw err;
if (results[0]) {
userId = results[0].user_id;
getUser("username", userId, function(err, data) {
if (err) {
console.log("ERROR : ", err);
} else {
email = data.value1;
username = data.value2;
getPosts("posts", 1, function(err, data) {
if (err) {
console.log("ERROR : ", err);
} else {
postName = data.value1;
postText = data.value2;
res.render('logged_in', {
email: email,
username: username,
pstname: postName,
psttxt: postText
}
});
}
});
} else {
res.render('index', {
validation: "failed"
});
}
});
});

How to insert signup data in node js

exports.signup = function (req, res) {
// For security measurement we remove the roles from the req.body object
delete req.body.roles;
// Init user and add missing fields
var user = new User(req.body);
user.provider = 'local';
user.displayName = user.firstName + ' ' + user.lastName;
// Then save the user
user.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
// Remove sensitive data before login
user.password = undefined;
user.salt = undefined;
req.login(user, function (err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user);
}
});
}
});
};
I am not understood the meaning of the below 2 lines in my code
1) delete req.body.roles;
2) req.login(user, function (err) {
an any one please give me the valid explanantion

Mongoose - use findOne multiple times at once

Disclaimer: I am a newb web dev.
I am creating a registration page. There are 5 input fields, with 3 of them (username, password, and email) requiring that they pass various forms of validation. Here is the code:
router.post('/register', function (req, res, next) {
user.username = req.body.username;
user.profile.firstName = req.body.firstName;
user.profile.lastName = req.body.lastName;
user.password = req.body.password;
user.email = req.body.email;
User.findOne({email: req.body.email}, function(err, existingEmail) {
if(existingEmail) {
console.log(req.body.email + " is already in use")
} else {
User.findOne({username: req.body.username}, function(err, existingUsername) {
if(existingUsername) {
console.log(req.body.username + " is already in use");
} else {
user.validate({password: req.body.password}, function(err) {
if (err) {
console.log(String(err));
} else {
user.save(function(err, user) {
if (err) {
return next(err);
} else {
return res.redirect('/')
}
})
}
});
}
});
}
});
});
Basically it first checks to see if it is a duplicate e-mail; if it is a duplicate e-mail, it says so in the console.log. If it isn't a duplicate e-mail, it then checks the username.... and then goes onto the password.
The issue is that it does this all one at a time; if the user inputs an incorrect email and username, it will only say that the email is incorrect (it won't say that both the email and username are incorrect).
How can I get this to validate all 3 forms at the same time?
You can use async to run them in parallel and it will also make your code cleaner and take care of that callback hell:
var async = require('async');
async.parallel([
function validateEmail(callback) {
User.findOne({email: req.body.email}, function(err, existingEmail) {
if(existingEmail) {
callback('Email already exists');
} else {
callback();
}
}
},
function validateUsername(callback) {
User.findOne({username: req.body.username}, function(err, existingUsername) {
if(existingUsername) {
callback('Username already exists');
} else {
callback();
}
}
},
function validatePassword() {
user.validate({password: req.body.password}, function(err) {
if(err) {
callback(err);
} else {
callback();
}
}
}
], function(err) {
if(err) {
console.error(err);
return next(err);
} else {
user.save(function(err, user) {
if (err) {
return next(err);
} else {
return res.redirect('/');
}
});
}
}
);
This way, all the validation methods inside the array will be run in parallel and when all of them are complete the user will be saved.
If you use else statements, you choose to make checks individually (one at a time) by design.
To achieve an 'all at once' behaviour, I would not use else statements (where possible, i.e. errors ar not fatal for next checks), but would do all tests in the same block, and would fill an object like this:
errors: {
existingEmail: false,
existingUserName: false,
invalidUserName: false,
wrongPassword: false,
...
};
And then I'd use it in the form to show user all errors together...
Something like this:
var errors = {};
if (existingEmail) {
console.log(req.body.email + " is already in use");
errors.existingEmail: true;
}
User.findOne({username: req.body.username}, function(err, existingUsername) {
if (existingUsername) {
console.log(req.body.username + " is already in use");
errors.existingUsername: true;
} else {
user.validate({password: req.body.password}, function(err) {
if (err) {
console.log(String(err));
errors.invalidUsername = true;
} else {
user.save(function(err, user) {
if (err) {
return next(err);
} else {
return res.redirect('/')
}
})
}
});
}
});

Resources