You asked about using async
and doing the first sort in memory rather than going to the database twice. You can try this (I haven't tested it). It uses Underscore to do the sorting.
_ = require("underscore");
async = require("async");
// ...
var newPageOrders = req.body.order;
// Get the pages in their original order
Page.find({}, {}, { sort: { 'order' : 1 } }, function(err, pages) {
if (err) return res.send(err);
// Set the order on the pages to the new order
pages.forEach(function (page, index) {
page.order = newPageOrders[index];
});
// Use the Underscore library to sort the list of pages by its new ordering
pages = _.sortBy(pages, 'order');
// Now that we've sorted the pages, normalize the order numbers
pages.forEach(function (page, index) {
page.order = index*10
});
// Save all of the pages
async.forEach(pages, function (page, callback) {
// Save the page. Pass in the callback which async provides us with,
// so that async knows when the page is saved
page.save(callback);
}, function (err) {
// This function is only called once all of the pages are saved
if (err) res.send(err);
else res.redirect('/admin/pages');
});
});