【问题标题】:Search multiple attributes in Mongo with Meteor使用 Meteor 在 Mongo 中搜索多个属性
【发布时间】:2017-06-09 15:23:26
【问题描述】:

我已经能够在 Meteor 中实现一个发布方法,该方法在订阅 template.js 时通过给定属性运行对我的 mongo 集合的查询,这工作正常,但现在我想添加一个多属性搜索以相同的方式。因此,假设我在 Mongo 中有一个集合,其中的文档都具有相同的属性但具有不同的值。

{batch:'HAHT020614' color: 'blue', material: 'plastic', printing: true, 
  model: 'H100', handle: 'plastic', product: 'C010' }
{batch:'HBTH060614' color: 'red', material: 'metal', printing: false, 
  model: 'V400', handle: 'metal', product: 'P001' }
...

我正在尝试将一个对象发送到包含所有用户通过反应变量选择的字段的发布方法:

Template.inventory.onCreated( function appBodyOnCreated() {
    this.searchQuery = new ReactiveVar({
        color: anyItem,
        batch: anyItem,
        model: anyItem,
        material: anyItem,
        handle: anyItem,
        printing: anyItem,
        product: anyItem,
    });
    this.autorun(function () {
        let template = Template.instance();
        template.subscribe("stock.search", template.searchQuery.get());
    });
});

然后在publication.js中:

Meteor.publish('stock.search', function stockQuery(search) {
  return Stock.find(
    { $and: [
      {color: { $regex : search.color }},
      {batch: { $regex : search.batch}},
      {product: { $regex : search.product}},
      {model: { $regex : search.model}},
      {material: { $regex : search.material}},
      {handle: { $regex : search.handle}},
      {printing: { $regex : search.printing}}
      ]
    }, 
    { limit: 10, sort: { batch: 1 } });
});

问题在于,根据用户的需要,某些搜索字段将在应用程序中使用或不使用,寻找可以搜索所有项目,例如蓝色和制造或金属,然后混合并匹配任何需要查找的内容。

对象正确到达发布方法,我能够提取属性,但问题出在查询中,因为我不知道是否可以要求 Mongo 将某些属性与“任何”匹配。我尝试将 { $exists: true } 作为默认属性(并且当搜索字段为空时)传递,以便它与集合中的任何文档匹配,但查询似乎没有正确返回。在这种情况下,我将正则表达式用作某种“包含”,而 var anyItem 只是一个空字符串。

是否有适当的方法来查询 mongo 以仅将某些属性与所选值匹配,而其他属性保持为“任何”?

【问题讨论】:

    标签: javascript mongodb meteor


    【解决方案1】:

    您可以只将非空条件传递给发布方法,并仅使用给定条件构建查询,如下所示:

    Meteor.publish('stock.search', function stockQuery(search) {
       const criteria = Object.keys(search).map(k => ({ [k]: { $regex: search[k] } }));
       return Stock.find(
           { $and: criteria }, 
           { limit: 10, sort: { batch: 1 } }
       );
    });
    

    【讨论】:

    • 我必须更改一些逻辑以捕获该值,但稍作调整后效果很好!谢谢!
    猜你喜欢
    • 2016-07-30
    • 2018-08-17
    • 2012-12-05
    • 2014-11-08
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    • 2018-05-06
    • 2021-05-18
    相关资源
    最近更新 更多