Search code examples
node.jscallbacknode-mongodb-native

Create user, callback


1st post. I'm a student studying js and came across this problem with a callback that I'm not sure how to structure properly.

var bcrypt = require('bcrypt-nodejs');
var users = db.collection("users");
this.addUser = function(username, password, email, callback) {
    "use strict";

    // Generate password hash
    var salt = bcrypt.genSaltSync();
    var password_hash = bcrypt.hashSync(password, salt);

    // Create user document
    var user = {'_id': username, 'password': password_hash};

    // Add email if set
    if (email != "") {
        user['email'] = email;
    }

    // NOT SURE What to write here
    callback(Error("addUser Not Yet Implemented!"), null);

}

Solution

  • First of all: do not use sync methods if possible, use callbacks instead.

    var bcrypt = require('bcrypt-nodejs');
    var users = db.collection("users");
    this.addUser = function(username, password, email, callback) {
       "use strict";
    
       // Generate password hash
       bcrypt.genSalt(function(err, salt) {
           if (err) {
               callback(err);
               return;
           }
           bcrypt.hash(password, salt, function(err, password_hash) {
               if (err) {
                   callback(err);
                   return;
               }
    
               // Create user document
               var user = {
                   '_id': username,
                   'password': password_hash
               };
    
               // Add email if set
               if (email != "") {
                   user['email'] = email;
               }
    
               // NOT SURE What to write here
               callback(null);
           });
       });
    }
    

    and please ask precise questions. If I understand propperly, you dont know how to handle a callback? you simply pass the function that will be called after all work in your function is done as the parameter callback. when your done, you call the callback with the wanted parameters. here it's the err object in case of an error or null if there is no error.

    If you want to pass your created user to the callback, just replace callback(null); with callback(null, user);