JavaScript promises were introduced to alleviate the problem of callback hell, and the newer async/await syntax was introduced to improve upon promises and eliminate the heavy nesting in callbacks and sometimes in promises.
Your code returns data from inside a callback, so you can’t just assign the data to a variable as the return value of the outer function.
If you want to check the data and use them, you need to do so from inside the callback.
And mongoose model find method returns an array of objects, not a string.
So I would do something like this if I was using the callback syntax:
findPeopleByName('John', (err, data) => {
if (err) {
return console.log(err);
}
if (data.length === 0) {
return console.log('No person with the name John was found.');
}
const personA = data[0];
if (personA.name === 'John') {
// Do something with personA
}
});
And if I was using the async/await syntax, I’d do something like this:
(async () => {
try {
const peopleFound = await Person.find({ name: 'John' });
if (peopleFound.length === 0) {
return console.log('No person with the name John was found.');
}
const personA = peopleFound[0];
if (personA.name === 'John') {
// Do something with personA
}
} catch (err) {
console.log(err);
}
})();
But now that I think about it, checking for name John is redundant because Person.find({ name: ‘John’ }) would only return Johns or an empty array.
But if you want to check for some other property such as personA.age > 25, I would do so as in the conditional as in the above code samples.
Here are some code examples of using mongoose with callbacks vs. async/await:
https://www.codepedia.org/ama/cleaner-code-in-nodejs-with-async-await-mongoose-calls-example