Skip to content

Ignore undefined fields in Collection.find() #1284

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 5, 2015

Conversation

tkers
Copy link
Contributor

@tkers tkers commented Aug 4, 2015

I noticed when calling the find(selector, fields) method on a collection with fields set to undefined, I get a TypeError: Object.keys called on non-object. When checking out the problem, I found that the collection.js module checks if argument.length >= 2 which evaluates to true even if argument[1] is not explicitly set. I.e. the code is trying to use the fields argument as if it's set, throwing the error eventually.

Fixed it by comparing fields !== undefined instead of using the argument count.

In our application, we basically do something like this:

// fields is optional
function getRecords(arg1, arg2, fields) {
    // validate arg1, arg2 etc...

     // build the query with arg1, arg2
    var query = {};

    return collection.find(query, fields);
}

I changed fields to fields || {} as a quick work-around for now, but I'm pretty sure undefined should be just ignored in the module.

@tkers tkers changed the title Ignore undefined fields in find method Ignore undefined fields in Collection.find() Aug 4, 2015
@christkv
Copy link
Contributor

christkv commented Aug 4, 2015

this is legacy behavior you should use. I support it as best as possible but the code is brittle so any changes like these breaks behavior that unfortunately people still relay on.

db.collection('data').find({}).project({a:1}).toArray()

@tkers
Copy link
Contributor Author

tkers commented Aug 5, 2015

I understand your point of view, although in this particular situation I have my doubts that developers could rely on this behaviour. You just wouldn't expect a function to try and parse a argument that is not really passed to it.

To be honest I'm not completely sure why JS also counts undefined values in arguments.length, maybe there is actually a good reason for this. But I think that for most use cases you shouldn't check if an optional parameter is passed or not in this way. Just as a future consideration then :)

Anyway, I wasn't aware that this is a legacy way of using the module. Will update my code accordingly. Thanks for the quick response!

@christkv christkv merged commit d631978 into mongodb:2.0 Aug 5, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants