0

USER SCHEMA:

{
    friends: [{
        user_id: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User'},
        name: {type: String, required :true},
        age: {type: Number, required: true}
    }],   
    privacy_settings : {
        visibility : {type : Number, enum: [0,1,2]},
        permission : {type : Number, enum : [0,1]},    
    }
}

Above is a sub section of user schema. I want to filter out the friends whose user id's don't exist. Right now what I get is:

QUERY RESULT:

  friends: 
   [ {},
     {},
     {},
     {},
     {},
     { user_id: 570f733f0e3fbfb7690b2384 },
     {},
     {},
     { user_id: 570f52b30e3fbfb7690b09f4 },
     {},
     {},
     {},
     { user_id: 570f57490e3fbfb7690b0afe },
     { user_id: 571072576952b11f0320f324 } ],

The problem is I don't want these {}, just the data where user_id exists.

QUERY USED

 user.findOne(
     {_id: some_mongoose_id},
     {'friends.userid privacy_settings'}, function(err,result){
          console.log(err,result);
     }
 )

How can I go about this ?

chridam
  • 100,957
  • 23
  • 236
  • 235
Nikhil
  • 467
  • 10
  • 22

1 Answers1

0

Try This:

user.find({"friends.user_id" : {$ne : null}},function(err,data){
if(data){
//console.log(data);
}
});
Shantanu Madane
  • 617
  • 5
  • 14
  • This will not work in my case..actually the condition clause is matching with _id not friends.userid... friends.userid is lying within the document found with _id matched with provided value...i want to filter the array of friends based on available userid from mongoose itself not taking it to be processed by node – Nikhil May 27 '16 at 13:25