javascript - 使用 Meteor 在 Mongo 中搜索多个属性

标签 javascript mongodb meteor

我已经能够在 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' }
...

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

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 将某些属性与“any”匹配。我尝试将 { $exists: true } 作为默认属性(当搜索字段为空时)传递,以便它与集合中的任何文档匹配,但查询似乎无法正确返回。在本例中,我使用正则表达式作为某种“包含”,而 var anyItem 只是一个空字符串。

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

最佳答案

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

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 } }
   );
});

关于javascript - 使用 Meteor 在 Mongo 中搜索多个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44461501/

相关文章:

javascript - mongodb nodejs - 转换循环结构

MongoDB 在多个字段上建立索引

java - 如何配置 persistence.xml 以指向 MongoDB

javascript - 如何避免同一事件的重复执行?

javascript - 按下 ALT 键时如何在 Javascript 中进行检测?

javascript - 隐藏 Fiori Master 详细信息页面中的批准/拒绝按钮

javascript - 在 Firefox 中有效但在 IE 中无效的 jQuery

javascript - 如何在 MTableToolbar 上应用 disableGutters Prop ?

javascript - Bootbox HTML 渲染

meteor - 可以更改 Meteor.loginWithPassword 以返回一般错误吗?