是否可以在我的查询中使用自定义属性作为条件

时间:2014-05-16 03:57:04

标签: node.js sails.js waterline

我想知道,是否可以在风帆中使用自定义属性来查询某些记录? 也许我下面的例子会更好地解释它。

模型/ user.js的

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

模型/ ModelA.js

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

我的查询

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

先谢谢你们。

1 个答案:

答案 0 :(得分:0)

不,Waterline在查询期间不会评估实例方法。在评估标准时,它也无法访问填充的模型;即this.user将为空。您需要在没有find属性的情况下执行studentName,然后自行过滤结果:

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

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

});

如果这是一个真实的例子,最好搜索用户模型,填充 ModelA

User.find(
    {or: [
        {firstName: {contains: searchKeyword}}, 
        {lastName: {contains: searchKeyword}}
    ]}
).populate('modela').exec(...)
相关问题