I am using Mongoose to create a user model in the database. When I return the user model to the browser, I would like to remove certain fields such as Salt and Password Hash.
I am using the Javascript delete keyword, but it is not deleting these properties.
I have written two examples.
Example 1 (Works): Create User Object with Salt, delete salt
describe('Manual User Object', function () {
it('should delete salt', function (done) {
// MANUALLY CREATE JAVASCRIPT OBJECT
var entity = { name: 'david', 'salt': 'yes please' };
l.kv('typeof entity', typeof entity);
l.kv('typeof entity.salt', typeof entity.salt);
l.line('before delete');
l.inspect(entity);
l.info();
l.line('delete entity.salt');
var isDeleted = delete entity.salt;
l.kv('Is Successful', isDeleted );
l.info();
l.line('after delete');
l.inspect(entity);
});
});
Example 2 (NOT Working): User Object created in Mongoose with Salt
Create User Controller Function
// ------------------------------------------------------------
// CREATE: Creates a new user in the DB.
// ------------------------------------------------------------
exports.create = function (req, res) {
//var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
//console.log(fullUrl);
try {
UserSchema.create(req.body.entity, function (err, entity) {
if (err) {
return mong.handleError(res, err);
}
// Fails to remove Salt
entity = santitise(entity);
return res.status(201).json(mong.formatSuccess(entity));
});
} catch (e) {
console.log(e);
}
};
Failing Unit Test it('should create an ' + modelName, function (done) {
var payload = td.users.newEntity('David', 'david@test.com', 'orderer', 'password');
request(app)
.post('/api/users')
.send(mong.wrapEntity(payload))
.expect(201)
.expect('Content-Type', /json/)
.end(function (err, res) {
if (err) {
l.logTheUnknown(err);
return done(err);
}
var document = res.body;
var entity = document.entity;
l.logDocument(document);
logEntity(entity);
utest.expectSuccess(document);
utest.expectTimeStampsOnCreate(entity, modelName);
// Check properties are returned
entity.should.have.property('name', 'David');
entity.should.have.property('email', 'david@test.com');
entity.should.have.property('role', 'orderer');
entity.should.have.property('provider', 'local');
//entity.should.have.property('password', 'david@test.com');
//entity.should.not.have.property('hashedPassword');
entity.should.not.have.property('salt');
return done(err);
});
});
Sanitise Function // THIS ENTITY HAS COME THROUGH FROM MONGOOSE.CREATE function santitise(entity) {
l.kv('typeof entity', typeof entity);
l.kv('typeof entity.salt', typeof entity.salt);
l.line('before delete');
l.inspect(entity);
l.info();
l.line('delete entity.salt');
var isDeleted = delete entity.salt;
l.kv('Is Successful', isDeleted);
l.info();
l.line('after delete');
l.inspect(entity);
return entity;
}