Nodejs mongodb限制带有选项的字段

时间:2015-12-11 10:38:30

标签: node.js mongodb

我有一个MongoDB的NodeJS应用程序。我想结合以下两个操作,但我遇到了麻烦。

将字段限制为仅名称:

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

输出:

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

要对我使用的值进行排序:

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

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

输出:

[
    {
        _id: "5668ea4646175538320c1ad7",
        email: "george@gmail.com",
        name: "George"
    },
    {
        _id: "565c9f1ad5015e516ea99b91",
        email: "kenneth@gmail.com",
        name: "Kenneth"
    }
]

基本上我想要以下内容:

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

1 个答案:

答案 0 :(得分:3)

只需将两个选项(fieldssort)合并为一个对象:

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

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