Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor.js : How to run check() when arguments are Mongodb ObjectId's?

Tags:

mongodb

meteor

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 !

like image 249
Petrov Avatar asked Dec 31 '13 01:12

Petrov


3 Answers

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.

like image 71
sbking Avatar answered Oct 14 '22 12:10

sbking


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

like image 30
Brad M Avatar answered Oct 14 '22 13:10

Brad M


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)
like image 32
waitingkuo Avatar answered Oct 14 '22 13:10

waitingkuo