jsonnode.jssails.js

Hide some properties in JSON response object in sails.js


I'm very new to sails.js framework. I want to hide some particular fields in the response JSON object when it gets queried.

For example, I have a model object User:

User: {
  name: 'Paul',
  email: 'paul@gmail.com',
  token: 'sdffsdf',
  id: 1
}

I want hide "token" property in case if this user is queried by GET request: localhost:1337/user?id=1

Can somebody give me a hint how to do that?


Solution

  • Overwrite the toJSON() function of your model. This can also be used to hide other sensitive data.

    module.exports = {
        attributes: {
            name: 'string',
            email: 'email',
            token: 'string',
            toJSON: function() {
                var obj = this.toObject();
                delete obj.token;
                return obj;
            }
        }
    }