2
\$\begingroup\$

I am using Mongoose ODM and NodeJS to implement CRUDL operations on MongoDB for further use with REST API. Initially, I've implemented functions using Promises but then switched back to callback style.

My questions are:

  1. Should I stick to traditional callbacks or to the default Promises? In this context, I got back to callbacks while I didn't profit from using Promises as callbacks are not so complex.
  2. When I pass data to that CRUDL functions, should I check that data in those functions or should it be checked before passing by a caller?
  3. I have noticed that when Mongoose doesn't find any matches, it doesn't throw the error, but returns null. Is it okay to check for that null in function and then throw another error that the user is not found like I implemented, or it is the job of the caller?

userModel.js

var mongoose  = require('mongoose');
var bcrypt = require('bcrypt');
var Schema = mongoose.Schema;
const SALT_WORK_FACTOR = 10;

var userSchema = new Schema({
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    },
    name:{
        type: String
    }
});


userSchema.pre('save', function(next){
    var user = this;

    if(!user.isModified('password')){
        return next();
    }

    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt){
        if(err){
            return next(err);
        }

        bcrypt.hash(user.password, salt, function(err, hash){
            if(err){
                return next(err);
            }

            user.password = hash;
            next();
        });
    });
});

module.exports = mongoose.model('User', userSchema);

userActions.js

var User = require('../../models/userModel');

module.exports.create = function(data, callback){
    var user = new User({
        email: data.email,
        password: data.password,
        name: data.name
    });
    user.save(function(err, user){
        if(err){
            callback(err);
            return;
        }
        callback(null, user);
    });
};


module.exports.read = function(key, callback){
   User.findOne({email:key}, function(err, user){
       if(err){
           return callback(err);
       }

       if(!user || user === 'undefined'){
           return callback(new Error('User has not been not found!'));
       }

       callback(null, user);
   });
};


module.exports.update = function(key, data, callback) {
    User.findOne({email: key}, function (err, user) {
        if(!user || user === 'undefined'){
            return callback(new Error('User has not been found!'));
        }

        if(data.email){
            user.email = data.email;
        }

        if(data.password){
            user.password = data.password;
        }

        if(data.name){
            user.name = data.name;
        }

        user.save(function(err, user){
            if(err){
                return callback(err);
            }
            callback(null, user);
        });
    });
};


module.exports.delete = function(key, callback){
    User.remove({ 'email' : key}, function(err, object){
        if(err){
            return callback(err);
        }
        if(object.result.n === 0){
            return callback(new Error('Element has not been deleted!'));
        }
    });
};


module.exports.list = function(callback){
    User.find({}, function(err, users){
        if(err){
            return callback(err);
        }
        if(users.length === 0){
            return callback(new Error('Users have not been found!'));
        }
        callback(null, users);
    });
};

How I make calls:

test.js

var mongo = require('./libs/db/mongo');
var userActions = require('./libs/db/userActions');
var debug = require('debug')('test.js');

mongo.connect('mongodb://localhost/test').once('open', function(){
    console.log('Connected to database!');

    var userData = {
        email: 'testmail1',
        password: 'testpass',
        name: 'testname'
    };

    userActions.create(userData, function(err, user){
        if(err){
            debug('MongooseError: ' + err);
            return;
        }
        debug('User has been created: ' + user);
    });

    var userEdit = {
        email: 'testmail_edit',
        password: 'testpass_edit',
        name: 'testname_edit'
    };

    userActions.update('testmail', userEdit, function(err, user){
        if(err){
            debug('MongooseError: ' + err);
            return;
        }
        debug('User has been edited: ' + user);
    });

    userActions.delete('testmail3', function(err){
        if(err){
            debug('MongooseError: ' + err);
            return;
        }
        debug('User has been deleted!');
    });


    userActions.read('testmail', function(err, user){
        if(err){
            debug('MongooseError: ' + err);
            return;
        }
        debug('User has been found: ' + user);
    });

    userActions.list(function(err, users){
        if(err){
            debug('MongooseError: ' + err);
            return;
        }
        debug('Users have been found: ' + users);
    });
});
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.