在Sails Waterline中查找数组包含字符串的记录

时间:2018-01-24 18:21:16

标签: node.js sails.js waterline

型号:

module.exports = {
  attributes: {
    title:{
      type:  'string',
      required: true,
    },
    content:{
      type:  'string',
      required: true,
    },
    tags: {
      type: 'array'
    }
  }
};

现在我想找到所有文章,其中给定的字符串在标签中。

我尝试了this

Article.find({tags: { contains: ["some1"]}}).exec(function(err,result){
    console.log(result);
});

但它找不到任何东西。

我正在使用sails-disk。我也试过$ in和$或(Waterline方式)。

2 个答案:

答案 0 :(得分:1)

我的理解是,对数组属性的水线查询将条件应用于数组的每个元素。因此,如果tags属性是字符串数组,则预期的行为将是:

Article.find({tags: 'hello'}).exec(function(err, results) {
    // results has all articles with a tag 'hello'
});

Article.find({tags: ['hello', 'hi']}).exec(function(err, results) {
    // results has all articles with a 'hello' or 'hi' tag
});

Article.find({tags: {contains: 'hello'}).exec(function(err, results) {
    // results has all articles with a tag containing substring 'hello'
});

我使用sails-mongo这样的水线,并按预期工作。

答案 1 :(得分:0)

如果你做另一个名为"标签"的模型会更好。并且关联"文章"用它。 Sails将创建"加入表" (或其他方法)现在您可以查询填充值。看看:docs

你可以做Tag.find(criteria).populate('Articles').exec(...)

之类的事情
相关问题