dayuloli
dayuloli

Reputation: 17011

Meteor - How to specify fields to return AND sort?

From the MongoDB docs, I know you can specify the fields to return using something like this:

db.products.find( { qty: { $gt: 25 } }, { item: 1, qty: 0 } )

And you can sort the rows using sort()

db.bios.find().sort( { name: 1 } )

However, several solutions on SO suggests this format:

DrawingHistory.find({}, {sort: {time: -1}});
Aphorisms.find({}, {sort: {date_created: -1}});

So I tried these, but none worked:

return Questions.find({}, {text: 1, options: 1}).sort({order: 1}); // Returns nothing
return Questions.find({}, {text: 1, options: 1}, {sort: {order: 1}}); // Doesn't work
return Questions.find({}, {sort: {order: 1}}, {text: 1, options: 1}); // Only first filter gets applied

Example document/row:

{
    "options": [
        {
            "answer": "Answer I",
            "value": "A"
        },
        {
            "answer": "Answer II",
            "value": "B"
        },
        {
            "answer": "Answer III",
            "value": "C"
        },
        {
            "answer": "Answer IV",
            "value": "D"
        }
    ],
    "order": 1,
    "text": "Question A"
}

Question

So, what is the correct way to specify fields to return AND sort at the same time in Meteor?

Upvotes: 3

Views: 2521

Answers (1)

richsilv
richsilv

Reputation: 8013

You're trying to use mongo shell API queries, which are somewhat different from the Meteor find API. In Meteor, options are all passed in the second argument:

Questions.find({}, {
    fields: {
        text: 1, 
        options: 1
    },
    sort: {
        order: 1
    }
});

Upvotes: 7

Related Questions