Hi I am creating a Login Page using Node js and MongoDB, I am really having problem creating the login route.
Here's my HTML Body
<body>
<div >
<div ></div>
<div ></div>
</div>
<form action="/login" method="post">
<h3>D.E.T Login</h3>
<label for="username">Username</label>
<input type="text" name="login_username" placeholder="Email or Phone" id="username">
<label for="password">Password</label>
<input type="password" name="login_password" placeholder="Password" id="password">
<button type="submit">Log In</button>
<button><i ></i>   Log In using Google</button>
<p>New User ? <a href="/register">Sign Up</a></p>
</form>
</body>
I am using findOne method to search for the same email in my database like this..
mongoose.connect("mongodb://localhost:27017/loginDB", { useNewUrlParser: true });
const userSchema = new mongoose.Schema({
email: {type: String},
pass: {type: String},
})
const User = new mongoose.model("User", userSchema);
app.post("/login", (req, res) => {
// get the data
const name = req.body.login_username;
const pass = req.body.login_password;
let a = User.findOne({email: name}).exec();
if(a){
console.log('found');
// let b = a.pass;
// console.log(b);
res.redirect("/")
}else{
console.log('not f');
}
});
Here's my problem, no matter whatever enter in the login page's email box my code gives output as user found even if the same email is not in the database.. can you tell me what am i doing wrong and how should i correct it
CodePudding user response:
Actually the problem is with the line on the search query.
The search query is asynchronous i.e. User.findOne().exec()
returns a promise and not a value.
And a promise is always not null (stored in variable a).
To get an actual document stored in the database
You need to change your code to either using .then()
app.post("/login", (req, res) => {
// get the data
const name = req.body.login_username;
const pass = req.body.login_password;
User.findOne({email: name}).exec().then((a)=>{
if(a){
console.log('found');
// let b = a.pass;
// console.log(b);
res.redirect("/")
}else{
console.log('not f');
}
})
});
or use async await
app.post("/login", async (req, res) => {
// get the data
const name = req.body.login_username;
const pass = req.body.login_password;
let a = await User.findOne({email: name}).exec();
if(a){
console.log('found');
// let b = a.pass;
// console.log(b);
res.redirect("/")
}else{
console.log('not f');
}
});
CodePudding user response:
You can pass a callback function to the exec
function.
app.post("/login", (req, res) => {
// get the data
const name = req.body.login_username;
const pass = req.body.login_password;
let a = User.findOne({email: name}).exec(function(err, res){
if(err) console.log(err)
else {
console.log('found');
// let b = a.pass;
// console.log(b);
res.redirect("/")}
});
});
CodePudding user response:
let dbResult = await Schema.admin.findOne({ email: req.body.email });
if(dbResult){
// code here
}else{
// code here
}