Sunday 28 May 2017

Mongoose express - sort order with populate

How do I send through a sorted list of documents with mongoose when using the populate function?

The high level structure for my data is Project > Task > Todo item.

I'm currently attempting to find a list of tasks for a given project, then for each task that is found I'm populating the associated todo items. This is working as expected, however I'm now trying to sort the todo items by their "rank" (each todo has an integer representing its rank).

The below piece of code is working to a certain extent...the todo items are coming back in the correct order, but grouped by the parent Task.

How can I apply a top level sort that provides the true sorted list of todo items?

Task.find().where("project.id").equals(req.params.id).populate({path: "todos", options: {sort:{"rank": 1}}}).exec(function(err, projectTasks){
    if (err) {
        console.log(err);
    } else {
    res.render("tasks/show", {currentUser: req.user, tasks: projectTasks});

        }
    });

Thanks!



via R.James

No comments:

Post a Comment