Mongoose findOne async

I tried many ways to get the following code to work. I’ve tried async/await, .then, straight code with no decorations. The function loginPerson always returns before the findOne executes.

app.post(’/login’, function (req, res) {
// console.log(‘Login Requested’);
if (db.loginPerson(req.body.userId, req.body.password)) {
console.log(‘Login successful’);
} else {
console.log(‘Login failed’);
}
});

exports.loginPerson = function (userId, password) {
console.log(userId);
console.log(password);

const query = PersonModel.findOne({ userId });
query.then(function (foundPerson) {
	console.log(foundPerson);
});
return true;

};

when you deal with “async” function, you need to “await” everywhere needed or use “then/catch” blocks everywhere you have them.

in this block of code, your “function” needs to be “async” and you have to “await” for “db.loginPerson”, or move success/fail messages along with login logic into then/catch blocks.

follow the same in your loginPerson function. either use async/await (not then/catch) or make it a Promise and resolve/reject depending on the query result.