linsongyang linsongyang - 5 months ago 41
AngularJS Question

How to pass json query object from client to server for Meteor collection find

I have a complex query that depends on user inputs from client, then I form a json object to query the collection, and invoke the Meteor.subscribe again with the updated query.

For example as in the following mongo db collection:

{ _id: 1, results: [ { product: "abc", manufacturer: "mfg 1" }, { product: "xyz", manufacturer: "mfg 2" } ] }
{ _id: 2, results: [ { product: "abc", manufacturer: "mfg 3" }, { product: "xyz", manufacturer: "mfg 4" } ] }
{ _id: 3, results: [ { product: "abc", manufacturer: "mfg 5" }, { product: "xyz", manufacturer: "mfg 6" } ] }


user enter product: "xyz", and manufacturer: "mfg 2", I create a query JSON object like the following:

scope.searchTerms = {};
scope.searchTerms.results = {};
var match = {};

match.product = "xyz";
match.manufacturer = "mfg 2";

searchTerms.results.$elemMatch = match;

Meteor.subscribe("products", scope.searchTerms));


Then, I have two problems:


  1. Server always return the full set of records;

  2. The searchTerms always contain proto.



I copied the content of searchTerms, and then hard code for the server to publish, and it works perfectly fine.

Products = new Mongo.Collection('products');
Meteor.publish('products', function (selector) {
return Products.find(selector);
});


Please help.

Answer

To answer my own question, I have finally found the problem.

For the match object to pass onto mongo, we cannot simply assign the values like the following:

var match = {};

match.product = "xyz";
match.manufacturer = "mfg 2";

We have to do a different way:

var match = {};

match['product'] = "xyz";
match['manufacturer'] = "mfg 2";

It is really weird.