Mongoose, Select a specific field with find

Javascriptnode.jsMongodbMongoose

Javascript Problem Overview


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???

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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.

Solution 4 - Javascript

Tip: 0 means ignore & 1 means show.

Example 1:

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

Example 2:

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

Example 3:

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

Solution 5 - Javascript

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

link

Solution 6 - Javascript

Exclude

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

Below code will only retrieve email field within each document:

const users = await UserModel.find({}, {
  email: 1
});
console.log(users);

Output

[  {    "email": "[email protected]"  }]

Solution 7 - Javascript

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

Solution 8 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTlonXPView Question on Stackoverflow
Solution 1 - JavascriptNeil LunnView Answer on Stackoverflow
Solution 2 - JavascriptAakashView Answer on Stackoverflow
Solution 3 - JavascriptElvinDView Answer on Stackoverflow
Solution 4 - JavascriptNishant ShahView Answer on Stackoverflow
Solution 5 - JavascriptRatan Uday KumarView Answer on Stackoverflow
Solution 6 - JavascriptziishanedView Answer on Stackoverflow
Solution 7 - JavascriptAshhView Answer on Stackoverflow
Solution 8 - JavascriptSteve F.View Answer on Stackoverflow