簡體   English   中英

模擬mongodb的排序方式

[英]Simulating mongodb's sorting method

在 mongodb 中,您可以像這樣從數據庫中獲取數據:

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

您可以將排序方法附加到find()以根據指定字段對數據進行排序,1 表示升序,-1 表示降序,如下所示:

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

我試圖了解它是如何工作的,並自己模擬它 但到目前為止我無法弄清楚他們如何設法將自定義sort()方法附加到另一個返回數組的方法,或者至少他們如何設法覆蓋原始的內置數組sort()方法,使其接受 object 參數,該參數指定我們將用於排序的屬性

我試圖模擬find()方法,所以我讓它返回一個帶有自定義sort()的 class ...但問題是現在我的find()不返回數據數組,而是返回一個 object,所以我將不得不更深入地挖掘以獲得實際的數據數組。我嘗試了什么:

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

我希望能夠通過find()而不是find().data訪問數據

我還嘗試了另一種方法,通過將自定義排序方法附加到find()中的數據數組 .. 如下所示:

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

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

但這也導致返回的數據數組有一些可以迭代的額外項目..我也不想要.-.

基本上..我想模擬 mongodb 的find().sort({prop:1})

如果你不使用 Mongoose,我推薦它,因為你可以做類似的事情

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

然后你可以做,

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

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

在該方法中,您實際上可以應用任何邏輯,包括對其他文檔進行單獨查詢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM