in my self-defined module I have this method which will query the db and find if the username exists in my db. I want some values to be returned so in the upper level I will know the query result.
var findUserbyUsername=function(username)
{
db.users.find({email:username},function(err,result)
{
if(err|!username) {console.log('username not found'); return 0;}
else return 1;
}
);
}
module.exports.findUser=findUserbyUsername;
in app.js I will call the above method like this
var lt=dbutil.findUser('xxxx@gmail.com');
but unfortunately I got undefined.... Can anyone help me workaround this ? Or any other suggestions ?
Your findUserbyUsername
function does not return anything, that is why you get undefined
. Since database operations are asynchronous in Node, then cannot return anything meaningful and work via callbacks. Change your code like this:
var findUserbyUsername = function(username, callback) {
db.users.find({ email: username }, function(err, result) {
if (err || !username) {
console.log('username not found');
callback(err? err: 'Username not found');
} else {
callback(null, whateverYouWantToReturn);
}
});
}
module.exports.findUser = findUserbyUsername;
and use it like this:
dbutil.findUser('xxxx@gmail.com', function(err, result) {
// you have the result from findUserbyUsername() in "result", and "err" is set if there was an error
});
(Note: I have also fixed your condition if(err|!username)
, since |
is a bitwise operator and you actually want the ||
logical operator)
(Edit: added de-facto standard err
parameter to the callback)
This is an asynchronous code, of course it's not going to return anything. You might want the following:
app.js:
dbutil.findUser( 'xx@gmail.com', function( err, data ) {
if ( err ) throw err;
// Handle the datas returned "data"
} );
module:
var findUserByUserName = function( username, callback ) {
db.users.find( { email: username }, function( err, result ) {
if ( err || !username ) {
console.log( 'username not found' );
// Call the function passed as parameter
callback( err ); // You give "undefined" as second parameter
}
else {
callback( err, result ); // You give the datas back
}
} );
} );
The issue is you have an asynchronous request inside your function, so the return inside the db.users.find is in the wrong scope, and will never get back to your request.
You need to pass a callback function as a second parameter so the code looks like this:
var findUserbyUsername=function(username, cb)
{
db.users.find({email:username}, cb);
}
module.exports.findUser=findUserbyUsername;
Then you can call the function like this:
dbutil.findUser('xxxx@gmail.com', function(err, username) {
if (err) {
// Handle err
} else {
// Handle username
}
})