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}).sele
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()
.
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);
});
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.
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);
}
});
Select method is used to select which fields are to be returned in the query result, excluding select means we want all the 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
To retrieve certain fields without retrieving the '_id' you can specify to exclude it
Model.find({}, {'Username':1, '_id':0}, function ( err, docs ){}.....