I'm trying to write a function to create a new user on my database (mongodb) and then return that user as an object which I defined. However, since the call to insert the user is async, result.nInserted is always undefined because the async code doesn't finish in time. Therefore, I never get to return my user. I would try and use callbacks to fetch the user after it is done being inserted, but then how would I be able to return that data from my original addUser function?
User.addUser = function(db, email, username, password, firstname, lastname, company, twitter){
var _id = new mongodb.ObjectID();
var result = db.get('users').insert({
_id: _id,
email : email,
verified : false,
password : password,
username : username,
firstname : firstname,
lastname : lastname,
company : company,
twitter : twitter,
rank : config.RANK_USER
});
return result.nInserted == 1 ? new User(_id, email, false, username, firstname, lastname, company, twitter, config.RANK_USER) : false;
};