Sails: Overloading `toJSON`, `this.toObject` is not a function

Created on 13 Nov 2015  路  2Comments  路  Source: balderdashy/sails

Following sailsjs.org or github.com/balderdashy/waterline-docs. With this model:

const User = {
    identity: 'user_tbl',
    connection: 'postgres',
    attributes: {
        email: {
            type: 'string',
            required: true
        },
        secret: {
            type: 'string',
            required: true
        },
        toJSON: () => {
            let user = this.toObject();
            delete user.secret;
            return user;
        }
    }
};

I tried [example one]:

module.exports = User;
/* # In main
import User = require('user');
waterline.loadCollection(Waterline.Collection.extend(User)) */

And [example two]:

module.exports = Waterline.Collection.extend(User);
/* # In main
import User = require('user');
waterline.loadCollection(User) */

With example one, Object.keys(this) === ['User'], and thus I get left with:

this.toObject is not a function.

With example two I can't even get to the toJSON call, because this error occurs:

Cannot read property 'findOne' of undefined when calling findOne.

Without overloading toJSON everything works fine in example one.

Most helpful comment

Just took another look, the issue was the type of function I'm using.

Swapping from => to function () fixed the issue. Seems that this is bound differently. Info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

All 2 comments

I don't know a whole lot about ES6 but using var should work here. It's run in a separate context - when JSON.stringify is ran so not sure what let does or gives you there.

Just took another look, the issue was the type of function I'm using.

Swapping from => to function () fixed the issue. Seems that this is bound differently. Info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Noitidart picture Noitidart  路  4Comments

MelwinKfr picture MelwinKfr  路  4Comments

visitsb picture visitsb  路  4Comments

mahfuzur picture mahfuzur  路  3Comments

radoslavpetranov picture radoslavpetranov  路  4Comments