Mongoose use of .select() method

前端 未结 9 1629
孤城傲影
孤城傲影 2020-12-14 14:16

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         


        
相关标签:
9条回答
  • 2020-12-14 14:40

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

    0 讨论(0)
  • 2020-12-14 14:40

    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);
    });
    
    0 讨论(0)
  • 2020-12-14 14:42

    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.

    0 讨论(0)
  • 2020-12-14 14:42

    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);
            }
        });
    
    0 讨论(0)
  • 2020-12-14 14:47

    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

    0 讨论(0)
  • 2020-12-14 14:49

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

    Model.find({}, {'Username':1, '_id':0}, function ( err, docs ){}.....
    
    0 讨论(0)
提交回复
热议问题