0

I'm wondering, is it possible to use a custom attribute in sails to query certain records? Maybe my example below will explain it better.

models/User.js

 attributes: { first_name: 'string', last_name: 'string' }

models/ModelA.js

 attributes: {
  user: {model: 'User'},
  studentName: function(){ return this.user.first_name + " " this.user.last_name },
  ....
 }

My Query

ModelA.find({studentName: {contains: searchKeyword }}).populate('user').then(console.log);

Thanks in advance guys.

ginad
  • 1,863
  • 2
  • 27
  • 42

1 Answers1

0

No, Waterline won't evaluate an instance method during a query. It also wouldn't have access to the populated model at the time that the criteria would be evaluated; i.e. this.user would be null. You'll need to perform the find without the studentName attribute, and then filter the result yourself:

ModelA.find().populate('user').exec(function(err, models) {

    models = _.where(models, function(model) {
        return model.studentName().match(searchKeyword);
    }

});

If this is a real example, it may be better to search User models instead, populating ModelA:

User.find(
    {or: [
        {firstName: {contains: searchKeyword}}, 
        {lastName: {contains: searchKeyword}}
    ]}
).populate('modela').exec(...)
sgress454
  • 24,870
  • 4
  • 74
  • 92