【问题标题】:Sails.js search by computed propertySails.js 按计算属性搜索
【发布时间】:2015-07-07 21:38:11
【问题描述】:

我正在用sails.js 编写API,但我在查找对象时遇到了一个问题。

我有带有属性的模型:

  attributes: {
    firstName:{
      type:"string",
      required:true,
      minLength: 2
    },

    lastName:{
      type:"string",
      required:true,
      minLength: 2
    },

    getFullName: function (){
      var fl =  this.firstName + " " + this.lastName;
      return fl;
    },
  }

现在我想用 getFullName startsWith "xyz qwe" 找到一个对象

我该怎么做?

我试过了:

Patient.find({ getFullName: { 'startsWith': 'Tomas' }}).exec(console.log)

Patient.find({ getFullName(): { 'startsWith': 'Tomas' }}).exec(console.log)

两者都不起作用。

我可以在 find() 函数中访问 getFullName 之类的计算属性吗?

这个查询当然有效:

Patient.find({ firstName: { 'startsWith': 'Tomas' }}).exec(console.log)

【问题讨论】:

    标签: sails.js


    【解决方案1】:

    exec 或回调有 2 个参数(与任何其他回调一样),它是 errorresult。所以你的代码应该是这样的。

    Patient
      .find({ getFullName: { 'startsWith': 'Tomas' }})
      .exec(function(err, founds){
        if(err) return console.error(err);
    
        console.log(founds);
      });
    

    或者你可以使用 Promise 链来做你之前做过的事情。

    Patient
      .find({ getFullName: { 'startsWith': 'Tomas' }})
      .then(console.log)
      .catch(console.error);
    

    【讨论】:

    • 没问题:.exec(console.log) 工作正常。问题是:如何在 find() 方法中使用计算属性(实例函数)。顺便提一句。我正在sails console 中对其进行测试,这就是我使用.exec(console.log) 的原因
    • 对不起,我误解了你的问题。如果我有时间并且仍然没有解决,我会稍后编辑我的答案。
    • 我已经通过复杂的查找查询解决了。但是我的问题比我的问题更复杂,请让我知道您对该问题的解决方案。我希望它会比我的更好。
    猜你喜欢
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 2017-07-31
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    相关资源
    最近更新 更多