0

I am making a little game in node.js and as database I am using mongodb with mongojs. Currently this is the way I am handling the database conenction:

var mongojs = USE_DB ? require("mongojs") : null;
var db = USE_DB ? mongojs('localhost:27017/dbName', ['players','pets']) : null;

And for example If I want to check if username is taken upon registration, I do:

Database.usernameCheck= function(name,callback){
    db.account.findOne({username:name.username},function(err,result){
        if(result) callback(true);
        else callback(false);
    });
}

And then I call the function when a new player is registered:

    Database.usernameCheck(data,function(result){
        if(result){
            //username taken        
        } else {
            //add the user
        }
    }); 

I am not too much experienced with the node.js and javascript programming, but I read that the best way to do is with promises, so I would like to convert my current code to use promises instead of callbacks. Tried a couple of ways, but I failed so I decided to ask here, well, thank you for your time.

Jakub Moz
  • 127
  • 10
  • Have a look at [this rather complete post](https://stackoverflow.com/questions/14220321), this should help you understand the concepts and the existing implementations. And give you enough insight to get to it! ;) – Stock Overflaw Feb 03 '19 at 04:26
  • Thanks, but I was actually hoping for example of accomplish the same concept using ex: mongoist or anything similar. – Jakub Moz Feb 03 '19 at 06:45
  • MongoJS team declares that this library has no support for promises, so you are stuck with callbacks for the mongoDB commands [clickhere](https://github.com/mafintosh/mongojs/issues/324) – Gabriel Lopez Feb 03 '19 at 07:11
  • I personally recommend Mongoose, it has a very similar approach and supports promises – Gabriel Lopez Feb 03 '19 at 07:14
  • @GabrielLopez that's why I said "example using ex: mongoist". I know that mongojs doesn't support promises. Can you please give me example using my code transformed for mongoose with promises? Thank you. – Jakub Moz Feb 03 '19 at 08:11
  • Got it to work switching to mongoose. Everything is better now. Thank you @GabrielLopez for the recommendation. – Jakub Moz Feb 03 '19 at 17:53

0 Answers0