我已經能夠在Meteor中實現一個發佈方法,它在訂閱template.js時通過給定的屬性向我的mongo集合運行查詢,該方法工作正常,但現在我可以喜歡以相同的方式添加多個屬性搜索。假設我在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 } });
});
問題在於,根據用戶的需求,某些搜索字段將在應用程序中使用或不被使用,尋找它可以搜索例如藍色和製成的所有項目或我tal,並且只需要混合和匹配任何必要的信息即可找到。
對象正確地到達發佈方法,我能夠提取屬性,但問題駐留在查詢中,因爲我不知道是否有可能要求Mongo將某些屬性與「any」匹配。我嘗試將{$ exists:true}作爲默認值(當搜索字段爲空時)傳遞,以便它與集合中的任何文檔匹配,但查詢似乎沒有正確返回。在這種情況下,我使用正則表達式作爲某種「包含」,而var anyItem只是一個空字符串。
有沒有一種合適的方法來查詢mongo,只將某些屬性與所選值相匹配,而其他屬性保持爲「any」?
我不得不改變了一下邏輯的事件捕獲價值,但有一點調整這個工作完美!謝謝! – Railoh