ChatGPT
ChatGPT

Reputation: 5617

How to sort a single field two different ways in Meteor Mongodb

OK I have a collection of tasks. Some have a dueDate and some do not (dueDate is missing). Is it possible to sort them, in a single find statement so that the are sorted dueDate asc followed by dueDate missing?

// desired sort result
red; 31 oct 2014
blue; 04 nov 2014
green; 15 nov 2015
purple; 
black;

Presently if I simply sort by dueDate, asc I get purple and black first. I want to force them to be last.

** EDIT **

I think i can do it if I can create a sort of calculated field called hasDueDate (true/false) then I can sort: {hasDueDate: 1, dueDate:1}. But it seems the only way to compute a field is with aggregation and it's not available from Meteor. Suppose I can set a hasDueDate using a collection trigger . . .

Upvotes: 1

Views: 158

Answers (1)

ChatGPT
ChatGPT

Reputation: 5617

Found a workaround. Using simpleSchema in Meteor I introduce a new field called isDueMissing which is automatically set on insert and update, like a trigger action.

fragment of the simpleSchema for my tasks:

  due: {type: Date, optional: true},

  isDueMissing: {
    type: Boolean,
    autoValue: function() {
      if (this.siblingField('due').isSet) {
        return false;
      } else {
        return true;
      }
    }
  },

now I can perform the desired sort like this:

Tasks.find({done: false}, {sort: {isDueMissing:1, due:1}},

enter image description here

Upvotes: 1

Related Questions