简体   繁体   中英

Sails.js : Add custom instace method result as a model property

I'm relatively new to JavaScript programming, so this problem may have a trivial solution. Working with Sails.js, I've created this model.

module.exports = {

    tableName: 'FOO_TABLE',

    attributes: {
        FOO: 'string',
        BAR: 'number',
        BAR2: function() {
            return this.BAR + 1;
        }
    },

};

Then, in a controller I get all the instances:

FOO_MODEL.find().exec(function(err, FOOS) {
    return res.view({data: JSON.stringify(FOOS)});
});

The problem is that inside FOOS, it's not the BAR2 method. I've come with this solution (using Underscore.js):

FOOS = _.map(FOOS, function(FOO){ FOO.BAR2 = FOO.BAR2(); return FOO; });

But I don't see it efficient / smart, as I think I will probably find this problem again. How would you do it? Thank you

If all you want is to set a calculated value for each new instance, you could set BAR2 to be of type number in the model (instead of a function), and add a beforeCreate class method like:

beforeCreate: function(values, cb) {
  values.BAR2 = values.BAR + 1;
  return cb();
}

If you want to keep BAR2 as an instance method, but have it serialized along with the object, you could override the default toJSON instance method:

toJSON: function() {
   var obj = this.toObject();
   obj.BAR2 = obj.BAR2();
   return obj;
}

Any time an instance is stringified, its toJSON method will be called.

Check Your Query Result

If you're calling your instance-method during a request, namely, within a query-callback -- you may want to check what result you are getting passed in.

In my case, I am using the Sails/Waterline ORM Model-method, find instead of findOne (like a bonehead), which actually argues a collection ( array ). So I was attempting something along the lines of:

[ {...} ].hasItem(id)

... while what I needed was something like:

myQueryResults[0].hasItem(id)

Or rather, query correctly using findOne . Idiocy is apparently a poor practice, but it happens I guess.

Hope this help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM