Search code examples
mongodbmongoosemongodb-querymongoose-populate

Sort whole collection then save in mongoose


I have a collection called "Forum".

I want to sort it by "forum_order" in ascending order then update whole collection sorted by "forum_order".

I tried following:

Forum.findByIdAndUpdate({}).sort({forum_order: 1}).exec(function(err, updatedTasks) { if (err) { console.log(err); } });

But didn't work.

enter image description here

If it was successful, "1st Forum" in the image should be above "3rd Forum" so that 1st Forum become 1st object in this 'forums' collection.

How can I fix this? I am new to mongodb...


Solution

  • This isn't really something that makes sense in mongo: there's no way of updating the default order that the documents get returned to you. When you don't specify a sort, they'll return in an order that's easy for mongo.

    Instead, you should specify the sort order when you find the documents: db.forums.find({}).sort({forum_order: 1});. If you have a large collection of fora, you may wish to add an index on forum_order.