Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sails.js User model not deleting password

Tags:

json

sails.js

I am trying to remove the password from the JSON serialized User model.

For some reason my controller returning res.json({user: myUser}); is returning the full user including the password. Below is my User model. Thoughts?

# models/User.js
var User = {
  attributes: {
    username: 'string',
    password: 'string'
  },

  // Override toJSON method to remove password from API
  toJSON: function() {
    var obj = this.toObject();
    // BELOW NOT WORKING
    delete obj.password;
    return obj;
  }
};
module.exports = User;
like image 622
Kevin Baker Avatar asked Sep 02 '14 09:09

Kevin Baker


1 Answers

You are adding toJSON as a class method (outside of the attributes object); it needs to be an instance method:

# models/User.js
var User = {
  attributes: {
    username: 'string',
    password: 'string',

    // Override toJSON method to remove password from API
    toJSON: function() {
      var obj = this.toObject();
      delete obj.password;
      return obj;
    }

  }

};
module.exports = User;

This will add the toJSON method to every instance of User, and will work as you expect when doing things like res.json().

like image 199
sgress454 Avatar answered Oct 28 '22 02:10

sgress454