Mongoose, Select a specific field with find
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???
The _id
field is always present unless you explicitly exclude it. Do so using the -
syntax:
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);
});
};
Or explicitly via an object:
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);
});
};
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 -
(minus sign). 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.
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.