Geoffry
Geoffry

Reputation: 25

Nodejs mongodb limit fields with options

I have a NodeJS application with MongoDB. I want to combine the following two operations but I am having trouble.

To limit fields to only names:

collection.find({}, {fields: {name:1}}, function(err, cursor){
    res.json(cursor);
});

Output:

[
    {
        _id: "565c9f1ad5015e516ea99b91",
        name: "Kenneth"
    },
    {
        _id: "5668ea4646175538320c1ad7",
        name: "George"
    }
]

To sort values I used:

var options = {"sort": "name"}

collection.find({}, options, function(err, cursor){
    res.json(cursor);
});

Output:

[
    {
        _id: "5668ea4646175538320c1ad7",
        email: "[email protected]",
        name: "George"
    },
    {
        _id: "565c9f1ad5015e516ea99b91",
        email: "[email protected]",
        name: "Kenneth"
    }
]

Essentially I want the following:

[
    {
        _id: "5668ea4646175538320c1ad7",
        name: "George"
    },
    {
        _id: "565c9f1ad5015e516ea99b91",
        name: "Kenneth"
    }
]

Upvotes: 1

Views: 804

Answers (1)

Dmytro Shevchenko
Dmytro Shevchenko

Reputation: 34581

Just combine the two options (fields and sort) into one object:

var options = {
    fields: { name: 1 },
    sort: "name"
};

collection.find({}, options, function(err, cursor) {
    res.json(cursor);
});

Upvotes: 3

Related Questions