Dittmar Consulting Dittmar Consulting - 6 months ago 23
Node.js Question

NodeJS & Mongoose - Stripping out code in a CRUD module doesn't get invoked

Coming from a JAVA background, callbacks can be still confusing for me.

Anyway, I have a simple Mongoose User Schema and I can create new users with the following code in the router.js

app.post('/signup', function(req, res){

var newUser = new User(req.body);

newUser.save(function(err){
if(err) res.send(err);

res.json(req.body);
});
});


Would it be nice if I could create a CRUD module (crudUser.js) for all user operations. Something like that:

var User = require('../dbmodels/userDBModel');

var _this = {};

_this.createUser = function(req, res) {

var newUser = new User(req.body);

newUser.save(function(err){
if(err) res.send(err);

res.json(req.body);
});
};

module.exports = _this;


and then just call this in the router.js instead:

var crudUser = require('../crud/crudUser.js');

app.post('/signup', crudUser.createUser);


but unfortunately the code in crudUser.js doesn't get invoked.

Does that work at all?

Thanks

Answer

you should set file name without Uppercase crudUser.js to cruduser.js then try change like this.

var User = require('../dbmodels/userDBModel');

exports.createUser = function(req, res) {

    var newUser = new User(req.body);

    newUser.save(function(err){
        if(err) res.send(err);

        res.json(req.body);
    });
};
Comments