Mongoose, select a specific field with find

I am 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 answer I also get _id, my document schema has only two types: _id and name

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

Why???

+46
javascript mongodb mongoose
Jun 22 '14 at 5:34
source share
4 answers

The _id field _id always present unless you explicitly exclude it. Do this 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 through the 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); }); }; 
+82
Jun 22 '14 at 6:09
source share

Now there is a shorter way:

 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 }; 

If you want most Schema fields and want to omit only a few, you can prefix the name field with - . For ex, "-name" in the second argument does not include the name field in the document, while the example given here will only have the name field in the returned documents.

+34
Sep 17 '15 at 12:52
source share

There's a better way to deal with 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.

+8
Oct 13 '15 at 16:35
source share
 db.someschema.find( { }, { name: 1 } ).exec(function(err,Result){ var NameArray = Result; console.log(NameArray); }) 

Output:

 [ {"name":"peter"}, {"name":"john"}, {"name":"joseph"} ] 
+1
Jun 25 '17 at 16:34 on
source share



All Articles