Masiar
Masiar

Reputation: 21352

Mongoose use of .select() method

I'm pretty confused with the use of the select method. This is how I use it, and it's wrong:

Transaction.find({username : user.username}).select('uniqueId', 'confirmation_link', 'item_name', 'timeout', 'username', function(err, txs){
        callback(txs);
});

What I'm trying to achieve is simply to select from the transactions in the database the ones with that username and I want to take out just the fields listed in the select method. Can anyone point out how should I use the select method? Thanks.

Upvotes: 68

Views: 169957

Answers (12)

Sam Thomas
Sam Thomas

Reputation: 1

.select() method is used to specify which fields you want to include or exclude from the query results. You can use a string value in parenthesis to specify which tags to use, the - operator when used in a string value can be used to exclude, while the use of the + operator in the string can be used to force inclusion of said query string I believe this is a mongoose method.

Upvotes: 0

Wovasteen Gova
Wovasteen Gova

Reputation: 58

set select: false for the fields that you want to exclude in your Schema on server request.

example

const userSchema = mongoose.Schema({
    name: {
        type: String,
        select: false
    },

    password: {
        type: Number,
        select: false

    }
})

that way the only fields that you want coming in should be the ones without select: false

If for some reason you need to get the password(any field) but need to have select: false in the schema. use select('+password etc')

Upvotes: 0

Mueed
Mueed

Reputation: 49

This syntax Also works

Transaction.find({username : user.username}).select(['uniqueId', 'confirmation_link', 'item_name', 'timeout', 'username']);

Upvotes: 3

Mayank
Mayank

Reputation: 301

Select method is used to select which fields are to be returned in the query result, excluding select means we want all the other fields to be returned, here is simple usage as per the docs.

// include a and b, exclude other fields  
query.select('a b');

// exclude c and d, include other fields  
query.select('-c -d');

More information here, https://mongoosejs.com/docs/api.html#query_Query-select

Upvotes: 20

Eric
Eric

Reputation: 9

Remove the commas and quotes between the fields you want to select:

Transaction.find({username : user.username}).select('uniqueId confirmation_link item_name timeout username', function(err, txs){
    callback(txs);
});

Upvotes: 0

Philipp Kyeck
Philipp Kyeck

Reputation: 18860

the docs say you can achieve this like so:

Mongoose v4.0

// Retrieving only certain fields

Model.find({}, 'first last', function (err, docs) {

});

old outdated API

// Retrieving only certain fields

Model.find({}, ['first', 'last'], function (err, docs) {
  // docs is an array of partially-`init`d documents
  // defaults are still applied and will be "populated"
});

so you can do this without select().

Upvotes: 97

Chanaka Fernando
Chanaka Fernando

Reputation: 2335

selection & projection operation can be done in this way easyly in nodejs. Try this

    var Selection={
        <some key of data model > : <target value for that key field>,
        <some key of data model > : <target value for that key field>
        //you can add many parameters here selection operation
        };
    var Projection = {
        __v    : false,
        _id    : false
        //you can add many parameters here for projection
    };
    <DataModel>.find(Selection,Projection,function (err,data) {
        if(err){
            console.log(err);
        }else{
         console.log(data);
        }
    });

Upvotes: 4

To retrieve specific fields only, use the following,

Model.find({/*Your query*/}, {'firstName':1, 'lastname':1, '_id':0}, //Notice, this will omit _id! function ( err, docs ){}.....

that will work and will NOT bring in any extra id such as _id.

Upvotes: 6

Alex Stubbs
Alex Stubbs

Reputation: 151

To retrieve certain fields without retrieving the '_id' you can specify to exclude it

Model.find({}, {'Username':1, '_id':0}, function ( err, docs ){}.....

Upvotes: 13

Felipe Pereira
Felipe Pereira

Reputation: 12320

Now there is a shorter way of doing this (not using .select and not using an array), just passing the fields separate by spaces as the second argument

User.find({}, 'first last', function (err, usr) {
    //Got the result, saved a few bytes of code
});

The Docs

Upvotes: 20

lee
lee

Reputation: 396

this is another way: queries in mongoose

Transaction.find({username : user.username})
.select('uniqueId confirmation_link item_name timeout username')
.exec(function(err, txs) {
        console.log(txs);
});

Upvotes: 26

tandrewnichols
tandrewnichols

Reputation: 3466

This was pretty helpful: How to protect the password field in Mongoose/MongoDB so it won't return in a query when I populate collections?

Looks like you have a few options.

1) Use select('-_id'). 2) Use find({whatever: values}, '-_id', callback...}. I can't verify this method, but if it works with select(), I don't see why it wouldn't work here.

Upvotes: 10

Related Questions