In some of my Meteor methods, I'm sending Mongodb ObjectId's from the client as arguments. I'd like to run these through Meteor's check() system but I can't seem to find anything that matches successfully with them.
I've tried
var someObjectId = Meteor.Collection.ObjectId();
check(someObjectId, Meteor.Collection.ObjectId()) // fails
check(someObjectId, { _str : String }) //fails
check(someObjectId, String) //fails
any help much appreciated !
Instead of:
check(someObjectId, Meteor.Collection.ObjectID());
Try without the parentheses:
check(someObjectId, Meteor.Collection.ObjectID);
Edit-
Note that the error message for this check isn't ideal.
check({}, Meteor.Collection.ObjectID);
// Error: Match error: Expected
You could assume the message should be something like
// Error: Match error: Expected ObjectId, got object
You can see why this happens in this snippet from the check package.
https://github.com/meteor/meteor/blob/devel/packages/check/match.js
if (pattern instanceof Function) {
if (value instanceof pattern)
return;
// XXX what if .name isn't defined
throw new Match.Error("Expected " + pattern.name);
}
Meteor.Collection.ObjectID
does not have name
property.
As an alternative solution, you could simply pass the hexadecimal string as an argument instead of the ObjectID.
var idValidator = Match.Where(function (id) {
check(id, String);
return /[0-9a-fA-F]{24}/.test(id);
});
check(new Meteor.Collection.ObjectID()._str, idValidator);
// success
check('', idValidator);
// Error: Match error: Failed Match.Where validation
check({}, idValidator);
// Error: Match error: Expected string, got object
check([], idValidator);
// Error: Match error: Expected string, got object <--- bug? I expect array
Note, this regular expression is pulled from here.
https://github.com/mongodb/js-bson/blob/master/lib/bson/objectid.js
You should use following to generate a random ObjectID:
var someObjectId = new Meteor.Collection.ObjectID();
As Cuberto said, you can then check it by Meteor.Collection.ObjectID
:
check(someObjectId, Meteor.Collection.ObjectID)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With