williamkapke / mongo-mock

Let's pretend we have a real MongoDB
MIT License
240 stars 74 forks source link

lib/collection.js fields sniff fails on limit 1 #93

Open Downchuck opened 5 years ago

Downchuck commented 5 years ago

This logic will fail when { limit: 1, fields: undefined } because well, that's what it'll do. Suggest checking for !(fields in args).

lib/collection.js

    case "object,object,function":
      //sniff for a 1 or -1 to detect fields object
      if (!args[1] || Math.abs(args[1][0]) === 1) {
        options.fields = args[1];
      }
      else {
        if(args[1].skip) options.skip = args[1].skip;
        if(args[1].limit) options.limit = args[1].limit;
        if(args[1].fields) options.fields = args[1].fields;
        if(args[1].projection) options.fields = args[1].projection;
      }
Downchuck commented 5 years ago

I'm pressed for time; here's the fix - note options.fields is set to args[1] earlier in the code, so it needs that else statement in as well, thus the if, else if, else.

      if (!("fields" in args[1]) && (!args[1] || Math.abs(args[1][0]) === 1)) {
        options.fields = args[1];
      }
      else {
        if(args[1].skip) options.skip = args[1].skip;
        if(args[1].limit) options.limit = args[1].limit;
        if(args[1].projection) options.fields = args[1].projection;
        else if(args[1].fields) options.fields = args[1].fields;
        else options.fields = {};
      }