2

i want to return (true,false) from this function, its returning object.. what i can do to return Boolean value ? this code is make a static method to users Module

users.statics.is_username_used = function(name) {
    return this.findOne({username: name}, function(error,doc){
        if(is_empty(doc)){
            return false;
        }else{
            return true;
        }
    });
};
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Azami Feb 13 '19 at 23:44
  • I see you are returning a function there. – MarkSkayff Feb 13 '19 at 23:53

2 Answers2

0

Use a callback function to return the boolean. For example, you can re-write the static as

// assign a function to the "statics" object of your usersSchema
usersSchema.statics.is_username_used = function(name, cb) {
    return this.findOne({username: name}, function(error, doc){
        if (err) return cb(err, null);
        return cb(null, !is_empty(doc));
    });
};

const User = mongoose.model('User', usersSchema);
User.is_username_used('someusername', (err, usernameExists) => {
    console.log(usernameExists);
});
chridam
  • 100,957
  • 23
  • 236
  • 235
0

In case you have Node.js 7.6+, you can use the async/await feature to make your function synchronous-like.

users.statics.is_username_used = async function(name) {
    var doc = await this.findOne({username: name});

    if (is_empty(doc))
        return false;

    return true;
};

Then the function is_username_used will be call with 'await' to get the boolean result:

var isUsed = await User.is_username_used('someusername');
Dee
  • 7,455
  • 6
  • 36
  • 70