mearvin
February 28, 2017, 6:06am
1
I recently added a RegExp serializer to EJSON, to be able to pass a query with a regex object from client to server. Something like this:
// client
var query = { tag: {$not: new RegExp("cre", "im")} };
Meteor.subscribe("posts", EJSON.stringify(query));
// Server
Meteor.publish("posts", function(query) {
...
cursor = Posts.find( EJSON.parse(query) );
...
});
This throws an Exception “MongoError: unknown operator: EJSON$type”
Here’s the repo
It seems that after parsing the query, it stringifies it internally and causing issues. Is this a bug? Is there a way around it?
In case someone else runs into a similar issue, here’s my workaround for now.
Meteor.publish("posts", function(query) {
var self = this;
...
rawPosts = Posts.rawCollection();
rawPosts.findSync = Meteor.wrapAsync(rawPosts.find);
rawPosts.findSync( EJSON.parse(query) ).sort ({ ... }).skip(...).limit(...).toArray(function(err, res) {
if (err) {
console.log(err);
return self.ready();
}
_.each(res, function(val) {
self.added("posts", val._id, val);
});
self.ready();
});
...
});
I’ve just stumbled into not being able to send RegExps to Meteor server.
I’ve ended with a far simpler solution: Simply stringify your RegExp via .toString()
, send it to the server and then parse it back to RegExp.