pouchdb: Sorting with selector $exists uses the wrong index

From @dolfje on September 8, 2016 10:27

When trying to sort on a field that is only selected by the $exists selector, gives an error.

testDB = new PouchDB(‘test’); testDB.createIndex({index: {fields: [“test”]}}).then(function() { return testDB.put({_id: “”+Math.random(), “test”: 5}); }).then(function() { return testDB.find({selector:{“test”: {$exists: true}}, sort: [“test”]}); }).then(function(ret) { // Expect result, only get //Error: Cannot sort on field(s) “test” when using the default index });`

Copied from original issue: nolanlawson/pouchdb-find#212

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 3
  • Comments: 22 (7 by maintainers)

Commits related to this issue

Most upvoted comments

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Why closing this issue ? I think this should be resolve without workaround as shown before…

I got this working by adding a gt: null with and selector like this :

db.createIndex({
  index: { fields: ['name'] }
}).then(() => {
  return db.find({
    selector: {
      $and: [
        { name: {'$gt': null} },
        { name: {'$exists': true} }
        // works on $regex too
        // { name: {'$regex': new RegExp('ndo', 'i')} }
      ]
    },
    sort: [{'name': 'desc'}],
    limit: 10
  });
})

I’ve solved this problem on my side, using JS function sort. Like this:

        db.find({
            selector:   {element_type: ET_PROJECT},
        }).then(function(res) {
            res.docs.sort(function(a, b) {
                if (a.fieldname > b.fieldname)
                    return 1;
                if (a.fieldname < b.fieldname)
                    return -1;
                return 0;
            });
            // ... here we can use res.docs sorted
        });

Note that this issue also happens when using the $type selector filter.