1

So I have this mongodb collection called stories and each of them has an index field which corresponds to their particular ordering amongst other stories. I want to be able to reorder order these stories on a GUI and subsequently update this ordering on my database but I can't seem to figure out the best way to do this. I know that something like this would be simple if the stories were for example stored in a LinkedList data structure but I don't see how I can do this with MongoDB collections.

As an example of what I am getting at, say for example I have this collection of stories

[
  {
    title: 'Story 1',
    index: 0
  },
  {
    title: 'Story 2',
    index: 1
  },
  {
    title: 'Story 3',
    index: 2
  },
]

And I wanted to reorder the list such that Story 1 comes after Story 3, then my result in the database would be

[
  {
    title: 'Story 2',
    index: 0
  },
  {
    title: 'Story 3',
    index: 1
  },
  {
    title: 'Story 1',
    index: 2
  },
]

and then if I wanted to delete Story 3 I would be left with

[
  {
    title: 'Story 2',
    index: 0
  },
  {
    title: 'Story 1',
    index: 1
  },
]

For reference, I am trying to implement this using Javascript and Mongoose

Faizan Virani
  • 134
  • 1
  • 11
  • Read this: [$sort](https://docs.mongodb.com/manual/reference/operator/aggregation/sort/) – Saif Jun 27 '18 at 04:24

1 Answers1

0

You can use following code to get the expected result.

  1. sort array using index :

model.find({ ... }).sort({ index: asc}).exec(function(err, model){ ... });

  1. delete an item :

you can find the particular documents using index - use findOne instead of find.

Kasunt
  • 45
  • 1
  • 10
  • Its not the querying I'm confused about but how to maintain the data in order when I need to things like reordering and deleting. Like how to readjust all the indices during these operations since reordering or deleting doesn't just affect the index of a single document. – Faizan Virani Jun 27 '18 at 13:46
  • see this link : https://stackoverflow.com/questions/5825520/in-mongoose-how-do-i-sort-by-date-node-js – Kasunt Jun 27 '18 at 14:13
  • I completely understand how to query a sorted list, my question is how to go about maintaining said sorted list, updating indexes as stories are inserted, deleted, and reordered. – Faizan Virani Jun 27 '18 at 16:34