猫鼬,用 find 选择一个特定的字段

我试图只选择一个特定的字段

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,我的文档模式只有两个字段,_ id 和 name

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

为什么?

317646 次浏览

除非显式排除,否则 _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);
});
};

现在有一个更简单的方法:

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前面加上一个 -(减号)。对于第二个参数中的 ex "-name"将在文档中包含 name字段,而这里给出的例子将在返回的文档中包含 只有name字段。

在 Mongoose 中使用本地 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 用户投影

此处列出的对象列表将不会返回/打印。

数据库数据

[
{
"_id": "70001",
"name": "peter"
},
{
"_id": "70002",
"name": "john"
},
{
"_id": "70003",
"name": "joseph"
}
]

质疑

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

产出:

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

工作样板操场

链接

实现这一点的精确方法是在新的 mongodbnodejs驱动程序中使用 强 > .project()光标方法。

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

排除

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

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"
}
]

提示: 0表示忽略,1表示显示。

例子一:

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

例二:

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

例三:

User.findById(id).select({ _id: 1, isActive: 1, name: 1, createdAt: 0 }).then(...)

我在猫鼬中发现了一个非常好的选项,它使用 很明显返回文档中所有特定字段的数组。

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