I'm implementing a simple local auth with express and MongoDB (using Mongoose) and for some reason the server sends back an empty response object for user, but the token gets sent in the response. I included a console.log statement immediately before the return to try and debug it a little bit, and the object logged there is the correct one with all of the data. This is what the create code looks like:
import mongoose from 'mongoose';
import jwt from 'jsonwebtoken';
import json from '../helpers/json';
var User = mongoose.model('User');
module.exports = function() {
var obj = {};
obj.create = function (req, res) {
var roles = ['authenticated'];
User.count({}, (err, len) => {
if (!len) {
roles.push('admin');
}
var user = new User(req.body);
user.roles = roles;
user.provider = 'local';
user.token = jwt.sign(user, global.config.secret, {expiresIn: 10800});
user.save((err, user) => {
if (err) {
return json.bad(err, res);
}
json.good({
record: user,
token: user.token
}, res);
});
});
};
return obj;
};
Like I said, I had included a console.log statement and the user will display properly.
If you are wondering, the json.good is a helper function that I wrote that basically looks like this
module.exports = {
good: function (obj, res) {
res.send({
success: 1,
res: obj
});
},
bad: function (err, res) {
var obj = {
success: 0,
res: err
};
if (obj.res.errors) {
obj.res.messages = [];
for (var i in obj.res.errors) {
obj.res.messages.push(obj.res.errors[i].message;
}
obj.res.messages = obj.res.messages[0];
}
res.send(obj);
}
};
I am also allowing the correct headers and methods in my express file. This code is identical to code that I have used before, but I am missing something it seems.
Update
I figured out the problem, it was in my model. I had
UserSchema.methods = {
toJSON: function() {
var obj = this.toObject();
delete obj.password;
delete obj.following;
}
};
I had forgotten to return the obj at the end. Thanks everyone!