Mongoose use of .select() method


Question

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.

1
37
3/3/2012 5:30:31 PM

Accepted Answer

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

65
2/13/2019 6:42:27 PM

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon