Maintain a custom order/sort of documents in MongoDB

只愿长相守 提交于 2020-06-29 03:19:30

问题


In my web app XY I'm showing a classic list/table of data (documents) to the user. While all the sort functions provided by MongoDB ( and Mongoose, i'm using Mongoose) are pretty clear to me, I'm not interested in sorting by date or alphabetical order. In my case it would be important to let the user maintain a custom sort as in manually drag/drop items around to set a specific order of the documents (e.g. putting favourites in top of the list ). The UI to do this is a no-brainer but how to actually save the order in the database, brain-freeze.

Problem : How would I go about saving such a custom order of documents ?

What I use : NodeJS / Express / Mongoose (MongoDB)


Ideas

So far I could think of 2 ideas on how to do this.

  • A : Having an additional key (e.g. orderKey) in the mongoose Schema. Big con : I would need to keep constantly updating all documents orderKeys. Also I would need some sort of auto-increment for new documents.
const mySch = new Schema({
   orderKey : { type : Number }
});
  • B : Creating one Schema/Model only for sorting, with an Array including all documents _ids for example. The order of the elements within the array would be used as reference for the custom order of the documents. Whenever the order changes, this Array would be changed as well.
conts orderSch = new Schema({
   orderArray : { type : Array }
}); 
mongoose.model('Order', orderSch);

/* const customOrder = new Order({
   orderArray : [ _id1, _id2, _id3, _id10, _id7, .. ]
}); */

Any more ideas or best practises are highly appreciated !

来源:https://stackoverflow.com/questions/59193436/maintain-a-custom-order-sort-of-documents-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!