Search code examples
node.jsmongoosemongoose-populate

lean() inside populate in mongoose


I am populating a user collection in mongoose and want to set a flag if the user is signed up using social accounts. So I am selecting that fields in populate. But due to security concerns I don't want to pass it in response. So I converted it into plain object using lean() and set the values as null. But once a values are set null for a particular user then it set that values null for that user_id. How set them null or how to hide them from response.

 Pins.find(condition)
   .limit(limit)
   .sort({time: -1})
   .populate({
     path: 'user_id',
     select: '_id name pic twitter_id fb_id',
     options: { lean: true}
   })
   .lean()
   .exec(function(err, data) {

        if(data){
         var flag = 0
            async.eachSeries(data, function(v, callback1) {

              if(v.user_id.twitter_id || v.user_id.fb_id ){
                  v.socialaccount=1
                  v.user_id.fb_id =''
                   v.user_id.twitter_id =''
              }else{
                  v.socialaccount=0 
                      v.user_id.fb_id =''
                   v.user_id.twitter_id =''
              }
             callback1()



     },function(){
              console.log(data)
             callback(data)  

            })

        } else {
            callback(data)
        }

    })

Thanks in advance


Solution

  • Here it is.

    Pins.find(condition)
      .limit(limit)
      .sort({time: -1})
      .populate({
        path: 'user_id',
        select: '_id name pic twitter_id fb_id',
        options: { lean: true}
      })
      .lean().exec(function(err, pins) {
      if(pins){
    
        pins = _.map(pins,function(pin) {
    
          //Setting the flag for social account
          pin.socialaccount = (pin.user_id.twitter_id || pin.user_id.fb_id );
    
          //Omitting the twitter_id and fb_id fields from user_id object
          pin.user_id.twitter_id = undefined;
          pin.user_id.fb_id = undefined;
          return pin;
       });
    
       return res.send(pins);
     }
    
    })
    

    I have mapped the pins collection from the find query such that you can set your socialaccount flag and can set the properties not required to undefined

    However i am not sure if you can use _.omit(pin.user_id,'twitter_id') instead of pin.user_id.twitter_id = undefined.Need to test that !

    The result pins collection will now have other user properties you wanted. Hope it helps :)