[英]Mongoose, Select a specific field with 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"}]
为什么???
_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
加上-
。 例如,第二个参数中的"-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/
笔记:
变量用户投影
此处列出的对象列表将不会返回/打印。
数据库数据
[
{
"_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"
}
]
工作示例游乐场
提示: 0 表示忽略,1 表示显示。
示例 1:
User.find({}, { createdAt: 0, updatedAt: 0, isActive: 0, _id : 1 }).then(...)
示例 2:
User.findById(id).select("_id, isActive").then(...)
示例 3:
User.findById(id).select({ _id: 1, isActive: 1, name: 1, createdAt: 0 }).then(...)
下面的代码将检索每个文档中除密码以外的所有字段:
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"
}
]
准确的方法是将.project()
游标方法与新的mongodb
和nodejs
驱动程序一起使用。
var query = await dbSchemas.SomeValue.find({}).project({ name: 1, _id: 0 })
我在 mongoose 中找到了一个非常好的选择,它使用不同的返回数组,所有文档中的特定字段。
User.find({}).distinct('email').then((err, emails) => { // do something })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.