问题
I have a mongo collection like the following (Foo(X) == keys; Bars == values): EDIT- I come from a relational database background. Obviously my collection doesn't look like the below, but you get the idea...
+--------+--------+--------+
| Foo1 | Foo2 | Foo3 |
+--------+--------+--------+
| Barbar | Barbar | Bar |
| bar | Bar | BarBar |
| Bar | barbar | barBar |
| ... | ... | ... |
It's important for me to allow my client to filter the data. Sometimes, all columns will have a filter, other times no columns will have a filter and anywhere in between. Currently, I'm handling the issue as follows:
Client
Var aFoo1Filter = ["bar"]
Var aFoo2Filter = ["Barbar", "BarBar"]
Var aFoo3Filter = ["barbar", "bar"]
//Where the user can affect the array through some other code
Server
Meteor.publish("foos", function (aFoo1Filter, aFoo2Filter, aFoo3Filter ) {
return FooCl.find({Foo1: {$in: aFoo1Filter},
Foo2: {$in: aFoo2Filter},
Foo3: {$in: aFoo3Filter}},
{limit: 10});
});
I'm hoping to simplify this by passing through just one object or one string from the client to the server, but neither attempts have worked. See my attempts, below:
Attempt #1 - Passing Through a String
Client
Var sFilter = "Foo1: {$in: [\"bar\"]},
Foo2: {$in: [\"Barbar\", \"BarBar\"]},
Foo3: {$in: [\"barbar\", \"bar\"]}"
Server
Meteor.publish("foos", function (sFilter) {
return FooCl.find({sFilter},
{limit: 10});
});
//////////////////
Attempt #2 - Passing Through an Object
Client
var oFilter = {
Foo1: "bar"
}
Server
Meteor.publish("foos", function (oFilter) {
return FooCl.find({oFilter},
{limit: 10});
});
I don't have my machine with me at the moment, so I can't provide more detail on the type of error thrown. Hopefully will have some more info up tonight. Thanks for any help!
回答1:
The easiest way to solve this problem is to subscribe using a selector:
Client
var selector = {Foo1: {$in: aFoo1Filter}, Foo2: {$in: aFoo2Filter}};
Meteor.subscribe('foos', selector);
Server
Meteor.publish('foos', function (selector) {
return FooCl.find(selector, {limit: 10});
});
However, it's important to recognize that this gives the client the ability to request any documents from the FooCl collection that she wants. An improved solution is to limit what can be requested by using match on the selector. For example:
Meteor.publish('foos', function(selector) {
check(selector, {
Foo1: Match.Optional({$in: [String]}),
Foo2: Match.Optional({$in: [String]})
});
if (!_.isEmpty(selector)) {
return FooCl.find(selector, {limit: 10});
}
});
This will ensure that selector conforms to an acceptable pattern before any documents are sent to the client.
来源:https://stackoverflow.com/questions/23937772/meteor-best-method-for-passing-mongo-selector-from-client-to-server