Mongoose use of .select() method

Javascriptnode.jsMongoose

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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().

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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

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

Solution 6 - Javascript

This was pretty helpful: https://stackoverflow.com/questions/12096262/how-to-protect-the-password-field-in-mongoose-mongodb-so-it-wont-return-in-a-qu

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.

Solution 7 - Javascript

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.

Solution 8 - Javascript

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

Solution 9 - Javascript

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

Solution 10 - Javascript

This syntax Also works

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

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
QuestionMasiarView Question on Stackoverflow
Solution 1 - JavascriptPhilipp KyeckView Answer on Stackoverflow
Solution 2 - JavascriptleeView Answer on Stackoverflow
Solution 3 - JavascriptFelipe PereiraView Answer on Stackoverflow
Solution 4 - JavascriptMayankView Answer on Stackoverflow
Solution 5 - JavascriptAlex StubbsView Answer on Stackoverflow
Solution 6 - JavascripttandrewnicholsView Answer on Stackoverflow
Solution 7 - JavascriptSheikh Zeeshan ShakeelView Answer on Stackoverflow
Solution 8 - JavascriptChanaka FernandoView Answer on Stackoverflow
Solution 9 - JavascriptEricView Answer on Stackoverflow
Solution 10 - JavascriptMueedView Answer on Stackoverflow