'Simulating mongodb's sorting method

In mongodb you get data from the db like this:

const allUsers = await User.find() // returns an array of users

You can attach a sort method to the find() to sort the data depending on the specified field, 1 for ascending, -1 for descending, like this:

const allSortedUsers = await User.find().sort({ rank: 1 }) // returns an array of users sorted by rank

I am trying to understand how this works, and simulate it by my own But I couldn't so far figure out how they managed to attach a custom sort() method to another method that returns an array, or at least how they managed to overwrite the original built-in array sort() method so that it accepts an object argument that specifies the property we will use to sort

I tried to simulate the find() method, so I made it return a class with a custom sort() ... but the problem is that now my find() doesn't return an array of data, but an object, so I will have to dig deeper to get the actual array of data.. what I tried:

function find() {
  const data = // finding logic
  return new DataClass(data)
}

class DataClass {
  constructor(data) {
    this.data = data
  }

  sort(sortByObject) {
    const sortedData = // sorting logic
    return sortedData
  }
}

const users = await find().data // returns the data
const sortedUsers = await find().sort({rank:1}) // returns the sorted data

I want to be able to access the data through find() and not find().data

I also tried another approach, by attaching a custom sort method to the data array in the find() .. like this:

function find() {
  const data = // finding logic

  // attaching a sort() function to the data array
  data.sort = function(sortByObject) {
    // sorting logic
  }
  return data
}

but this also caused the returned array of data to have something like an extra item that could be iterated over.. which I don't want either .-.

Basically.. I want to simulate mongodb's find().sort({prop:1})



Solution 1:[1]

If you are not using Mongoose, I recommend it, as you could do something like

const { Schema, model } = require('mongoose')
const objSchema = new Schema({...});

objSchema.methods._sort = function (key, ascending=false) {
  // sorting logic
}

const Obj = Model("Obj" objShcema)

module.exports = Obj

And then later you could do,

const Obj = require("path/to/export.js")

const found = Obj.findOne({...})
found._sort("some_field", true)

In the method, you can apply really any logic, including making separate queries to other documents.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ben10mexican