I'm trying to select only a specific field with
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);
});
};
But in my json response i'm receiving also the _id, my document schema only has two fiels, _id and name
[{"_id":70672,"name":"SOME VALUE 1"},{"_id":71327,"name":"SOME VALUE 2"}]
Why???
This question is related to
javascript
node.js
mongodb
mongoose
There is a shorter way of doing this now:
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
};
In case you want most of the Schema fields
and want to omit only a few, you can prefix the field name
with a -
. For ex "-name"
in the second argument will not include name
field in the doc whereas the example given here will have only the name
field in the returned docs.
Example 1:
0 means ignore
1 means show
User.find({}, { createdAt: 0, updatedAt: 0, isActive: 0, _id : 1 }).then(...)
Example 2:
User.findById(id).select("_id, isActive").then(...)
DB Data
[
{
"_id": "70001",
"name": "peter"
},
{
"_id": "70002",
"name": "john"
},
{
"_id": "70003",
"name": "joseph"
}
]
Query
db.collection.find({},
{
"_id": 0,
"name": 1
}).exec((Result)=>{
console.log(Result);
})
Output:
[
{
"name": "peter"
},
{
"name": "john"
},
{
"name": "joseph"
}
]
Working sample playground
Below code will retrieve all fields other than password within each document:
const users = await UserModel.find({}, {
password: 0
});
console.log(users);
Output
[
{
"_id": "5dd3fb12b40da214026e0658",
"email": "[email protected]"
}
]
Below code will only retrieve email field within each document:
const users = await UserModel.find({}, {
email: 1
});
console.log(users);
Output
[
{
"email": "[email protected]"
}
]
I found a really good option in mongoose that uses distinct returns array all of a specific field in document.
User.find({}).distinct('email').then((err, emails) => { // do something })
There's a better way to handle it using Native MongoDB code in Mongoose.
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/
Note:
var usersProjection
The list of objects listed here will not be returned / printed.
The precise way to do this is it to use .project()
cursor method with the new mongodb
and nodejs
driver.
var query = await dbSchemas.SomeValue.find({}).project({ name: 1, _id: 0 })
Source: Stackoverflow.com