MongoDB + Express: how to verify credentials with db.collection (). FindOne () or .find ()?

I have a POST request with the user credentials as an object from the login page and transferred to the API server like this:

loginUser(creds) { //creds is in the form of { username: bob, password: 123 } var request = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(creds), } fetch(`http://localhost:3000/api/login`, request) .then(res => res.json()) .then(user => { console.log(user); console.log('Successful') }) .catch(err => { console.log('Error is', err) }) }, 

And the API server gets it like this:

 //With .findOne() app.post('/api/login/', function(req, res) { console.log('Req body in login ', req.body) db.collection('users').findOne(req.body, function(err, isMatch) { console.log('ISMATCH IS: ' + isMatch) if(err) { console.log('THIS IS ERROR RESPONSE') res.json(err) } else { console.log('THIS IS ISMATCH RESPONSE') res.json(isMatch) } }) }) 

or

 //With .find() app.post('/api/login/', function(req, res) { console.log('Req body in login ', req.body) //console logs correctly as { username: bob, password: 123 } db.collection('users').find(req.body).next(function(err, isMatch) { console.log('ISMATCH IS: ' + isMatch) if(err) { console.log('THIS IS ERROR RESPONSE') res.json(err) } else { console.log('THIS IS ISMATCH RESPONSE') res.json(isMatch) } }) }) 

Thus, with the login credentials provided, inside the API server, I would like to search my 'users' database to see if any of them match. But in both cases, isMatch always null and always logs console.log('THIS IS ISMATCH RESPONSE') , even if the user credentials do not match any of the databases. And on the client side, I never get any error responses and console.log('Successful') always logged.

It may not seem that I am missing. What can i do wrong?

thanks

+5
source share
2 answers

I suggest that you first find the user and then compare the password, for example:

 db.collection('users').findOne({ username: req.body.username}, function(err, user) { console.log('User found '); // In case the user not found if(err) { console.log('THIS IS ERROR RESPONSE') res.json(err) } if (user && user.password === req.body.password){ console.log('User and password is correct') res.json(user); } else { console.log("Credentials wrong"); res.json({data: "Login invalid"}); } }); 
+1
source

You must use $ and Operator in . findOne () .

Working example:

 db.collection('users').findOne( { $and: [ { name: req.body.username.toLowerCase() }, { password: req.body.password } ] }, (err, result) => { if(err) { res.status(500).send(err); return; } if(!result) { data = { "meta": { "status": "fail", "message": "Login Failure: Invalid username or password" } }; res.status(401).send(data); } else { data = { "meta": { "status": "success", "message": "Login success" } }; res.json(data); } }); 
+1
source

Source: https://habr.com/ru/post/1257416/


All Articles