Wednesday, 19 April 2017

Does the $sort object in the nodejs aggregation framework API guarantee order?

I know keys order are not guaranteed in JS objects.

In the MongoDB Node.JS Driver I want to generate the $sort stage of the aggregation framework within a function and return an object to be piped: (e.g. { $sort: { field1: -1, field2: 1 } }).

const obj = [
  ['field1', 1],
  ['field2', -1]
]

function sortFunc (obj) {
  return obj.reduce((acc, x) => {
    acc[x[0]] = x[1]
    return acc
  }, {})
}

// => { $sort: sortFunc(obj) } => { $sort: { field1: 1, field2: -1 } }

How to be sure sortFunc(obj) will preserve order and will not return { $sort: { field2: -1, field1: 1 } } to the pipe?



via eakl

No comments:

Post a Comment