Mongoose,使用find选择特定字段

时间:2014-06-22 05:34:40

标签: javascript node.js mongodb mongoose

我尝试仅使用

选择特定字段
exports.someValue = function(req, res, next) {
    //query with mongoose
    var query = dbSchemas.SomeValue.find({}).select('name');

    query.exec(function (err, someValue) {
        if (err) return next(err);
        res.send(someValue);
    });
};

但是在我的json回复中我也收到了_id,我的文档架构只有两个fiels,_id和name

[{"_id":70672,"name":"SOME VALUE 1"},{"_id":71327,"name":"SOME VALUE 2"}]

为什么???

8 个答案:

答案 0 :(得分:134)

_id字段始终存在,除非您明确排除它。使用-语法执行此操作:

exports.someValue = function(req, res, next) {
    //query with mongoose
    var query = dbSchemas.SomeValue.find({}).select('name -_id');

    query.exec(function (err, someValue) {
        if (err) return next(err);
        res.send(someValue);
    });
};

或明确地通过一个对象:

exports.someValue = function(req, res, next) {
    //query with mongoose
    var query = dbSchemas.SomeValue.find({}).select({ "name": 1, "_id": 0});

    query.exec(function (err, someValue) {
        if (err) return next(err);
        res.send(someValue);
    });
};

答案 1 :(得分:56)

现在有一种更短的方法:

.rb

如果您想要大部分exports.someValue = function(req, res, next) { //query with mongoose dbSchemas.SomeValue.find({}, 'name', function(err, someValue){ if(err) return next(err); res.send(someValue); }); //this eliminates the .select() and .exec() methods }; 并且只想省略少数,则可以在字段Schema fields前加name作为前缀。对于第二个参数中的前- 包含文档中的"-name"字段,而此处给出的示例将包含 返回文档中的name字段。

答案 2 :(得分:19)

使用Mongoose中的Native MongoDB代码可以更好地处理它。

exports.getUsers = function(req, res, next) {

    var usersProjection = { 
        __v: false,
        _id: false
    };

    User.find({}, usersProjection, function (err, users) {
        if (err) return next(err);
        res.json(users);
    });    
}

http://docs.mongodb.org/manual/reference/method/db.collection.find/

注意:

  

var usersProjection

此处列出的对象列表不会被退回/打印。

答案 3 :(得分:7)

数据库数据

db.collection.find({},
{
  "_id": 0,
  "name": 1
}).exec((Result)=>{
    console.log(Result);
})

查询

[
  {
    "name": "peter"
  },
  {
    "name": "john"
  },
  {
    "name": "joseph"
  }
]

输出:

{{1}}

工作样本游乐场

Normalize.css vs Reset CSS

答案 4 :(得分:5)

示例1:

0表示忽略

1表示演出

User.find({}, { createdAt: 0, updatedAt: 0, isActive: 0, _id : 1 }).then(...)

示例2:

User.findById(id).select("_id, isActive").then(...)

答案 5 :(得分:3)

执行此操作的确切方法是将.project()光标方法与新的 mongodb nodejs 驱动程序配合使用。

var query = await dbSchemas.SomeValue.find({}).project({ name: 1, _id: 0 })

答案 6 :(得分:1)

排除

下面的代码将检索每个文档中除密码之外的所有其他字段:

const users = await UserModel.find({}, {
  password: 0 
});
console.log(users);

输出

[
  {
    "_id": "5dd3fb12b40da214026e0658",
    "email": "example@example.com"
  }
]

包含

下面的代码将仅检索每个文档中的电子邮件字段:

const users = await UserModel.find({}, {
  email: 1
});
console.log(users);

输出

[
  {
    "email": "example@example.com"
  }
]

答案 7 :(得分:0)

我发现猫鼬中一个非常好的选择,它使用 distinct 返回数组文档中所有特定字段。

User.find({}).distinct('email').then((err, emails) => { // do something })